skip to Main Content

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 );


    array(2) {
      'foo' => int(1)
      'bar' => int(2)

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

This Post Has 0 Comments

Leave a Reply

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

Back To Top