Table of Contents
Using Type Casting (Simple Objects)
Handling Private and Protected Properties
Converting Nested Objects or Complex Data
Home Backend Development PHP Tutorial How to convert an object to an array in PHP?

How to convert an object to an array in PHP?

Sep 14, 2025 am 03:14 AM
php array

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.

How to convert an object to an array in PHP?

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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Aisi Assistant's genuine download portal_Aisi Assistant's iPhone installation link Aisi Assistant's genuine download portal_Aisi Assistant's iPhone installation link Sep 16, 2025 am 11:30 AM

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.

Tips for searching for the entrance of Xiaohongshu Dandelion_Liaohongshu Dandelion official website access path Tips for searching for the entrance of Xiaohongshu Dandelion_Liaohongshu Dandelion official website access path Sep 16, 2025 pm 12:15 PM

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.

Google Earth's latest version is used online_Ultra-clear 3D globe without installation Google Earth's latest version is used online_Ultra-clear 3D globe without installation Sep 16, 2025 pm 12:39 PM

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 Reading Link_Xuanshu.com e-book online access address Xuanshu.com Reading Link_Xuanshu.com e-book online access address Sep 16, 2025 pm 02:27 PM

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.

How to check if an email address is valid in PHP? How to check if an email address is valid in PHP? Sep 21, 2025 am 04:07 AM

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

How to get the file extension in PHP? How to get the file extension in PHP? Sep 20, 2025 am 05:11 AM

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

How to log errors to a file in PHP? How to log errors to a file in PHP? Sep 17, 2025 am 04:21 AM

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

How to get the client's IP address in PHP? How to get the client's IP address in PHP? Sep 18, 2025 am 02:27 AM

TherealclientIPinPHPcanberetrievedusingaprioritizedcheckofHTTPheaderslikeHTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR,andHTTP_X_REAL_IP,fallingbacktoREMOTE_ADDR,withvalidationtopreventspoofing.

See all articles