Home >Backend Development >PHP Tutorial >How to Easily Convert a PHP Object into an Associative Array?

How to Easily Convert a PHP Object into an Associative Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 10:54:10618browse

How to Easily Convert a PHP Object into an Associative Array?

How to Convert a PHP Object to 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.

Simply Typecast the Object

To convert an object to an array, simply typecast it:

$array = (array) $yourObject;

Understanding the Resulting Array

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:

  • Integer properties: Inaccessible
  • Private variables: Prepended with the class name
  • Protected variables: Prepended with a '*'

Examples

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) {}
}

Limitations

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:

  • PHP documentation on Arrays: https://www.php.net/manual/en/function.array.php
  • StdClass object documentation: https://www.php.net/manual/en/class.stdclass.php
  • "Fast PHP Object to Array Conversion": https://stitcher.io/blog/fast-php-object-to-array-conversion

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!

Statement:
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