Skip to content

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;

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon

{ 1 } Comments

  1. MD. Fahim Murshed | March 6, 2010 at 11:43 am | Permalink

    Thanks Shiplu brother.
    It is really very useful thing.

{ 1 } Trackback

  1. [...] This post was mentioned on Twitter by A K M Mokaddim. A K M Mokaddim said: has just written a blog post Convert an PHP array to object http://bit.ly/6sSul3 [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *