...
CodeIgniter, Tutorials

How to Convert Array to Object and Object to Array in php

03 April 2019

In this post, I am going to explain about to create an array from the object and create object from array in PHP. This is easy if arrays and objects are one-dimensional, but might be little tricky if using multidimensional arrays and objects. Sometimes you get data in object form and you want to cast the object to the array.
Use this function to convert stdClass Objects into Arrays and Arrays to Objects:

Convert Objects to Array

Objects aren’t as easy to work with as arrays, so you may want to convert the returned object into a multidimensional array.Here,I am going to explain to convert object form data to an array. Using the following function you can cast the object form data.

<?php
    $employee_object = new stdClass;
    $employee_object->name = "John Doe";
    $employee_object->position = "Software Engineer";
    $employee_object->address = "53, nth street, city";
    $employee_object->status = "Best";

    function convert_object_to_array($object) {
        if (is_object($object)) {
            return (array) $object;
        } else {
            return $object;
        }
    }

    /* * * convert the object array ** */
    $array = convert_object_to_array($employee_object);

    /* * * show the array ** */
    print_r($array);
?>

Convert Array to Objects

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

    function convert_array_to_object($data) {
        if (is_array($data)) {
            return (object) array_map(__FUNCTION__, $data);
        } else {
            return $data;
        }
    }

    /* * * convert the array to object ** */
    $array = convert_array_to_object($arr);

    /* * * show the object** */
    print_r($array);
?>

This way of accessing properties via array conversion is quite useful when it actually makes sense to access object internal state.

Leave a Comments