Convert an PHP array to object

How do you convert an php array stdClass object?

Many times, we have to convert array to stdClass objects for easy access. Yeah, easy access. At least for me. Cause typing [“”] instead of -> requires 2 extra key press. I dont like that.

So how do you do it?

Its really simple, just cast the array with (object). It’ll become an stdClass.
See the following code,

$ar = array(
"age"=>27,
"name"=> "john",
"female"=>0
);
print_r($ar); // will print "Array" as type

// making it an object

$ob = (object) $ar;
print_r($ob); // will print "stdClass Object" as type

// compare the values.
if($ar["name"]===$ob->name)
echo "values are identical", PHP_EOL;
else
echo "values are not identical", PHP_EOL;
 

Author: shiplu

The Lone Explorer.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve * Time limit is exhausted. Please reload the CAPTCHA.