Current Location: Home> Latest Articles> How to Manipulate Object Properties After Converting Array to Object in PHP

How to Manipulate Object Properties After Converting Array to Object in PHP

M66 2025-07-29

Converting Array to Object and Manipulating its Properties

Arrays and objects are two commonly used data structures. In practical development, you often need to convert an array into an object for easier manipulation. This article will explain how to convert an array to an object and how to flexibly manipulate object properties after the conversion.

Array to Object Conversion

In PHP, one common way to convert an array to an object is by using the Object.assign() method. This method takes two parameters: the target object and the source object to copy from. After conversion, the array elements will become properties of the object.

const arr = ['foo', 'bar', 'baz'];

const obj = Object.assign({}, arr);

console.log(obj); // Output: {0: "foo", 1: "bar", 2: "baz"}

With the above code, elements in the array will be copied to a new empty object, and the indices 0 through 2 will become properties of that object.

Manipulating Object Properties

After converting the array to an object, you can access and modify the object's properties using dot notation or bracket notation.

console.log(obj.0); // Output: foo

console.log(obj['1']); // Output: bar

You can also modify the object's properties using assignment.

obj.2 = 'qux';

console.log(obj); // Output: {0: "foo", 1: "bar", 2: "qux"}

Real-World Use Cases

In real-world development, converting an array to an object can be applied in many scenarios. For example:

  • Converting array data returned from a server to an object for easier manipulation on the client side.
  • Storing form element values as objects, making it easier to submit the data.
  • Converting a list of data into an object for generating dynamic UI components.

Conclusion

By using the Object.assign() method, you can easily convert an array into an object. After conversion, the object supports both dot notation and bracket notation to access and modify its properties. This method provides great flexibility in various development scenarios, making it an indispensable tool.