Home >Backend Development >PHP Tutorial >How to Easily Convert a PHP Object into an Associative Array?
Integrating APIs that operate with data in objects can pose challenges if your code utilizes arrays. Fortunately, PHP offers a straightforward method to transform objects into associative arrays.
To convert an object to an array, simply typecast it:
$array = (array) $yourObject;
As mentioned in the PHP documentation:
"If an object is converted to an array, the result is an array whose elements are the object's properties."
However, certain properties may behave differently:
Simple Object:
$object = new StdClass; $object->foo = 1; $object->bar = 2; var_dump((array) $object);
Output:
array(2) { 'foo' => int(1) 'bar' => int(2) }
Complex Object:
class Foo { private $foo; protected $bar; public $baz; public function __construct() { $this->foo = 1; $this->bar = 2; $this->baz = new StdClass; } } var_dump((array) new Foo);
Output:
array(3) { 'Foofoo' => int(1) '*bar' => int(2) 'baz' => class stdClass#2 (0) {} }
Typecasting directly does not perform deep casting of the object graph. To access non-public attributes, you must apply the null bytes mentioned in the PHP manual. This method works best for casting simple StdClass objects or objects with public properties only.
For more in-depth information, consider reading the following:
The above is the detailed content of How to Easily Convert a PHP Object into an Associative Array?. For more information, please follow other related articles on the PHP Chinese website!