How to convert an object to an array in PHP?
Use (array) to convert simple objects into arrays. If they contain private or protected properties, the key names will have special characters; for nested objects, recursive functions should be used to traverse the conversion to ensure that all hierarchical objects become associative arrays.
To convert an object to an array in PHP, you can use a simple type casting method or a recursive approach depending on the complexity of the object.
Using Type Casting (Simple Objects)
If the object contains only public properties and no nested objects, type casting with (array) works directly.
$object = new stdClass(); $object->name = "John"; $object->age = 30; $array = (array) $object; print_r($array);
This outputs:
Array ( [name] => John [age] => 30 )
Handling Private and Protected Properties
When an object has private or protected properties, casting to array includes additional characters in the keys to indicate visibility.
- Private property myProp in class MyClass becomes "\0MyClass\0myProp"
- Protected properties become "\0*\0propertyName"
This can complicate access, so consider using getters or reflection if you need clean array keys.
Converting Nested Objects or Complex Data
For objects containing other objects or arrays, a recursive function ensures full conversion.
function objectToArray($data) { if (is_object($data)) { $data = get_object_vars($data); } if (is_array($data)) { return array_map('objectToArray', $data); } return $data; } // Example usage class Address { public $city = "New York"; public $zip = "10001"; } class Person { public $name = "Alice"; public $address; public function __construct() { $this->address = new Address(); } } $person = new Person(); $array = objectToArray($person); print_r($array);
This approach ensures all levels of nested objects are converted into associated arrays.
Basically, use (array) for simple cases, and a recursive function when dealing with complex or nested objects.
The above is the detailed content of How to convert an object to an array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



The official download portal of Aisi Assistant is located on the official website https://www.i4.cn/, and provides computer and mobile downloads, supporting device management, application installation, mode switching, screen projection and file management functions.

The entrance to the Little Red Book Dandelion can be accessed through the mobile app or computer. 1. Mobile: Open Xiaohongshu App, log in to an account that has completed real-name authentication, click "Me" to enter the personal center, find "Creation Center" or "Cooperation Center", click "More Services" and select "Blogger Cooperation" or "Dandelion Member" to enter; 2. Computer: Visit the official website https://in.xiaohongshu.com/, click "Login" in the upper right corner, and use the certified creator account to authorize login. The system automatically identifies the identity and enters the corresponding interface. New users need to submit their identity certificates, business licenses and other materials to complete their entry. The platform provides functions such as data analysis, blogger screening, cooperation management, content delivery and heating, and supports multiple cooperation modes.

The latest version of Google Earth online access is https://earth.google.com/web/, which supports global high-definition satellite images, 3D terrain, street panorama and historical image backtracking. It can operate smoothly in the browser without downloading, and can synchronize collection and custom landmarks through your account.

Xuanshu.com's reading link is https://www.xswang.com. The platform provides clearly classified novel resources, covering mainstream themes such as fantasy and cities, supports personalized reading settings and progress synchronization, and has a comment area and author interaction function to improve user reading experience.

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.

ConfigurePHPerrorloggingbysettinglog_errors=Onandspecifyingerror_logpathinphp.ini,thenuseerror_log()functiontomanuallylogerrorsorexceptionstoafile,ensuringthelogfileissecureandnotweb-accessible.

TherealclientIPinPHPcanberetrievedusingaprioritizedcheckofHTTPheaderslikeHTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR,andHTTP_X_REAL_IP,fallingbacktoREMOTE_ADDR,withvalidationtopreventspoofing.
