skip to Main Content
How To Convert PHP Objects (Public, Private, Protected) To Assoc Array

How To Convert PHP Objects (Public, Private, Protected) To Assoc Array

If you have an PHP Object & want to convert it to PHP Associative Array then you can below solutions. Each one has it’s own benefit & drawbacks..

Let’s say we have this simple PHP Object coming from Json we want to convert…

$obj = json_decode( '{"name": "Saj", "from": "BD"}' );

The simplest way to do that is typecasting, although this has drawbacks which it can’t convert private or protected object except public…

$ArrayFromObj = (array) $obj;

Let’s see some examples & solutions for converting all kinds of PHP Object To Assoc Array…

  • Solution 1
    $object = new StdClass;
    $object->foo = 1;
    $object->bar = 2;
    var_dump( (array) $object );

    Output:

    array(2) {
      'foo' => int(1)
      'bar' => int(2)
    }
  • Solution 2
    $array = json_decode(json_encode($php_object), true);
  • Solution 3
    function object_to_array($data)
    {
        if (is_array($data) || is_object($data))
        {
            $result = array();
            foreach ($data as $key => $value)
            {
                $result[$key] = object_to_array($value);
            }
            return $result;
        }
        return $data;
    }

Use anyone of those above method as per your need… if your object is very simple please use typecasting method for simplicity and performance boost. If you have a very large class with lots of object then might go for the Solution 2 and for more complex

Sajjad Hossain Sagor

A Self Motivated Web Developer Who Loves To Play With Codes...

Leave a Reply

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

Back To Top