search
HomeBackend DevelopmentPHP ProblemDiscuss type conversion between objects and arrays in PHP

In PHP, objects can be converted to arrays. This type conversion is very common because many times we need to convert the properties in the object to an array for easy use. In this article, we will discuss type conversion between objects and arrays in PHP and introduce some commonly used methods.

Convert object to array

In PHP, use the get_object_vars() function to convert an object to an array. This function will return an array containing the object's properties and property values, where the keys are the property names and the values ​​are the property values. For example, we can define an object with multiple properties and then convert it to an array:

class Person {
    public $name = '';
    public $age = '';
    public $email = '';
}

$person = new Person();
$person->name = 'Jack';
$person->age = 25;
$person->email = 'jack@example.com';

$person_array = get_object_vars($person);

print_r($person_array);

The output is as follows:

Array
(
    [name] => Jack
    [age] => 25
    [email] => jack@example.com
)

As shown above, we create an Person object, and three properties are set: name, age and email. Then, we convert this object to an array using the get_object_vars() function.

Convert array to object

We can also convert an array to object. Use (object) type conversion in PHP to achieve this operation. This method works with associative arrays, where the array's keys will become the object's property names, and the array's values ​​will become the object's property values.

$data = array(
    'name' => 'Tom',
    'age'  => 22,
    'email' => 'tom@example.com'
);

$person = (object) $data;

print_r($person);

The output result is as follows:

stdClass Object
(
    [name] => Tom
    [age] => 22
    [email] => tom@example.com
)

As shown above, we created an associative array $data, and then used the (object) function to Convert it to an object. The object type obtained after conversion is stdClass, which is a built-in standard type.

Mixing arrays and objects

In PHP, arrays and objects can be converted to each other, and they can be used together. For example, we can convert an object to an array, modify some of its properties, and then convert it back to the original object. This is particularly useful in some cases, such as when we need to modify the JSON data returned by an API and then serialize it into JSON format and return it.

$data = '{"name":"Tom","age":22,"email":"tom@example.com"}';
$person = json_decode($data);

$person_array = get_object_vars($person);

$person_array['age'] = 23;

$person = (object) $person_array;

echo json_encode($person);

The output results are as follows:

{"name":"Tom","age":23,"email":"tom@example.com"}

As shown above, we first use the json_decode() function to convert the JSON format string into an object. We then convert the object into an array $person_array and modify the values ​​within it. Finally, we use the (object) type conversion to reconvert the modified array to an object, and the json_encode() function to serialize the object into JSON string format.

Conclusion

In PHP, converting objects and arrays is a very common type conversion. Use the get_object_vars() function to convert an object to an array, and use the (object) type conversion to convert an array to an object. This type conversion is very practical and can be used in many projects. If you need to convert objects and arrays in PHP, these methods should help you.

The above is the detailed content of Discuss type conversion between objects and arrays in PHP. 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
How to Implement message queues (RabbitMQ, Redis) in PHP?How to Implement message queues (RabbitMQ, Redis) in PHP?Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices?What Are the Latest PHP Coding Standards and Best Practices?Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

How to Use Asynchronous Tasks in PHP for Non-Blocking Operations?How to Use Asynchronous Tasks in PHP for Non-Blocking Operations?Mar 10, 2025 pm 04:21 PM

This article explores asynchronous task execution in PHP to enhance web application responsiveness. It details methods like message queues, asynchronous frameworks (ReactPHP, Swoole), and background processes, emphasizing best practices for efficien

How to Use Reflection to Analyze and Manipulate PHP Code?How to Use Reflection to Analyze and Manipulate PHP Code?Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

How Do I Work with PHP Extensions and PECL?How Do I Work with PHP Extensions and PECL?Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance.PHP 8 JIT (Just-In-Time) Compilation: How it improves performance.Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

How to Use Memory Optimization Techniques in PHP?How to Use Memory Optimization Techniques in PHP?Mar 10, 2025 pm 04:23 PM

This article addresses PHP memory optimization. It details techniques like using appropriate data structures, avoiding unnecessary object creation, and employing efficient algorithms. Common memory leak sources (e.g., unclosed connections, global v

How Do I Stay Up-to-Date with the PHP Ecosystem and Community?How Do I Stay Up-to-Date with the PHP Ecosystem and Community?Mar 10, 2025 pm 06:16 PM

This article explores strategies for staying current in the PHP ecosystem. It emphasizes utilizing official channels, community forums, conferences, and open-source contributions. The author highlights best resources for learning new features and a

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

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.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment