In this post, I am going to explain about to create an array from the object in PHP.Sometimes you get data in object form and you want to cast the object to the array.The biggest change from PHP 4 to PHP 5 is the new object Oriented Program.
PHP is quite simple and easy to use .An object is defined by the class of which it is an instance of the programmer-defined class.To access the member variable, an object is to follow a variable containing the object with -> and then the name of the member.when you assign an object to a variable to a function the object is actually copied bit-for-bit into the variable or function scope.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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; } |
Many developers want to convert the object into an array for easy looping over a foreach somewhere in their code.You can attempt this in many ways. Here I just saw the one way which recursively converts your object into the array.
There are a few possible ways to convert the object into an array and each of them has its strengths and weaknesses. You can also use the following way.Using this way you can casting object with an array.
1 2 3 | $array = (array) $obj; |
The problem with this is, it doesn’t convert multi-dimensional objects well. That’s why I suggest using above custom function which converts any object to an array.
That’s it. You can add this function and use it when require. If you have any comments or suggestion about this post, I would really appreciate it.