Convert an array to an Object in PHP

Last Updated at : September 17, 2017 By - Usama Muneer | 2965

    Introduction

    Sometimes in PHP, you might find yourself needing to covert an array into an object. In this small hack, we’ll be seeing how easily this could be achieved.

    The Array

    Let us assume, you’re given an array of some property which contains an other array. Sounds complex? Well here you just have an array inside of an array.

    <?php
    $array =[
       'items' => [
          'foo',
      'bar'
     ]
    ];

    The Output

    On print_r the array, you might get the result something like

    array:1 [
      "items" => array:2 [
        0 => "foo"
        1 => "bar"
      ]
    ]

    Convert to an Object

    So let’s convert this array into an object. Here we’ll be using json_encode & json_decode. JSON is the JavaScript object notation & PHP provides us an ability to encode and decode JSON.

    – json_encode: For converting an array to a json string.

    – json_decode: For converting a json string into an object.

    Step 1 – Encode it to a string

    $object = json_encode($array);

    var_dump this object will get you something like:

    "{"items":["foo","bar"]}"

    This string of information might be useful for something like storing into the database.

    Step 2 – Decode it to an Object

    Now as we have a json string, we can use json_decode to convert and format this string in to an object. Let’s try that.

    $object = json_decode(json_encode($array));

    var_dump this object now will get you

    stdClass Object ( [items] => Array ( [0] => foo [1] => bar ) )

    One thing to note about json_decode is, it converts a json string to an object unless you provide a second option which is a boolean which maybe true or false. If you set the second parameter to “true”, you’ll still get an array.

    The Use Case

    Finally, we have successfully converted our array to an object, we can use it as

    foreach ($object->items as $item) {
       echo $item;
    }

    Try this little trick yourself and leave us a comment below if you have any queries regarding this.

    The Better way around

    Using JSON encode and decode for converting arrays to objects may consume a lot of resources if the array is bigger. In this way, the better way to cast an array into an object is using the object typecast. For example

    $object = (object)$array;

    This will also return

    stdClass Object ( [items] => Array ( [0] => foo [1] => bar ) )

    Its upto you whichever method to chose between the two for converting an array to an object in PHP.

     

    blog user
    Usama Muneer

    A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.

    Related Posts

    Laravel Live Islamabad, ended on 24th Nov'18 & we got a lot to learn from the top-notch of speakers & influencers. Thanks to the sponsors for pulling off such a great event in the capital of Pakistan.

    Inspired from Laravel's router, lets build our very own PHP's router for managing our endpoints well for our next PHP project.

    Another #LaraconUS in the books & It was the 6th instalment of #LaraconUS happened at Chicago with full swing & we got a lot to learn this time with exceptional line of speakers and never-ending community support by fellow Artisans

    Laravel is one of a famous and widely used PHP framework which is growing with immense pace since its version 4.2. Learning Laravel & Setting up your application locally is not much of a difficult task but when it comes to deployment, developers often find it a bit tricky to handle.