Home > Backend Development > PHP Tutorial > How Can I Quickly Convert PHP Objects to Associative Arrays?

How Can I Quickly Convert PHP Objects to Associative Arrays?

Susan Sarandon
Release: 2024-12-19 05:47:41
Original
755 people have browsed it

How Can I Quickly Convert PHP Objects to Associative Arrays?

Converting PHP Objects to Associative Arrays

While your API uses objects to store data, your code relies on arrays. To bridge this gap, you seek a quick way to convert objects into arrays.

The simplest method is to typecast the object into an array:

$array = (array) $yourObject;
Copy after login

By doing this, the object's properties become the keys of the resulting array.

Example:

$object = new StdClass;
$object->foo = 1;
$object->bar = 2;

var_dump((array) $object);
Copy after login

Output:

array(2) {
  'foo' => int(1)
  'bar' => int(2)
}
Copy after login

Important Notes:

  • Private Properties: Typecasting won't expose private properties in the array.
  • Protected Properties: Protected properties will have an asterisk (*) prepended to their names.
  • Nested Objects: Typecasting does not perform deep casting; nested objects remain objects in the array.
  • StdClass Objects: This method works best for StdClass objects or objects with only public properties.

For a more detailed blog post on PHP object-to-array conversion, refer to:

  • [Fast PHP Object to Array Conversion](https://www.sitepoint.com/fast-php-object-to-array-conversion/).

The above is the detailed content of How Can I Quickly Convert PHP Objects to Associative Arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template