In PHP, objects and arrays are two basic data types. Objects are an important part of object-oriented programming (OOP) languages, which allow us to combine data and functions to make them more convenient to use. In contrast, an array is an unordered collection that can hold many different types of data. In some cases, we may need to convert objects into arrays to perform some operations or facilitate output, so this article will focus on how to convert objects into arrays in PHP.
Generally speaking, PHP provides two ways to convert objects into arrays, namely using cast and using PHP built-in functions. The following are explained separately:
1. Use forced type conversion
Forced type conversion in PHP is very simple. You only need to place the value to be forced before the target data type to be converted. . The same goes for converting objects to arrays. The following is a sample code to cast an object to an array:
$obj = new stdClass(); $obj->foo = 'bar'; $obj->hello = 'world'; $arr = (array) $obj; print_r($arr);
Output result:
Array ( [foo] => bar [hello] => world )
As can be seen from the above code, by casting an object to an array, we can easily The properties of the object are converted into the key-value pair format of the array.
2. Use PHP built-in functions
Compared with forced type conversion, using PHP built-in functions to convert objects to arrays may be more convenient in some cases. PHP provides a get_object_vars()
function, which is used to obtain all non-static member variables of the specified object. We can convert the object into an array by directly assigning the value returned by this function to the array. The following is a sample code that uses this method to convert an object to an array:
class Person { public $name; public $age; private $gender; public function __construct($name, $age, $gender) { $this->name = $name; $this->age = $age; $this->gender = $gender; } } $obj = new Person('Alice', 25, 'female'); $arr = get_object_vars($obj); print_r($arr);
Output result:
Array ( [name] => Alice [age] => 25 )
As can be seen from the above code, use the get_object_vars()
function Converting an object to an array will only return the public properties of the object, while private and protected properties will not be returned.
It should be noted that when there are undefined attributes in the object, using the get_object_vars()
function will throw a traditional warning. Therefore, when using this method, you should first check whether the object has this property defined. Alternatively, you can also use the json_decode(json_encode($object), true)
method, which uses the get_object_vars()
function internally and is more rigorous in handling undefined attributes. . The following is a sample code that uses this method to convert an object to an array:
$obj = new stdClass(); $obj->foo = 'bar'; $obj->hello = 'world'; $arr = json_decode(json_encode($obj), true); print_r($arr);
Output result:
Array ( [foo] => bar [hello] => world )
In summary, converting a PHP object to an array can either use cast or You can use PHP built-in functions, all of which can easily convert the properties in the object into the format of array key-value pairs. No matter which method is used, you need to pay attention to whether the defined properties are public properties and whether there are checks for undefined properties.
The above is the detailed content of php convert object to array. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools