Create Array of Objects in PHP

An array can contain a sequence of elements of different data types. From strings to integers to floats to objects.

In this post, we will discuss the different ways to how to create an array of objects in PHP.

Using [] syntax

We can use the short array syntax – [] – to create an array of objects by passing the object variable names to it.

Output

Using array() method

We can simply use the array method to create an array of objects. All we need to do is simply pass objects as its arguments.

Output

We can also use this same approach for class objects. By developing a class and specifying some of its features, we can produce objects. There will be some values for the class’s properties. The properties and values will finally combine to create a key-value pair in the array.

Output

Here, we created Student class with 2 attributes, name and id.

Then created multiple objects and used array() to create array of objects in PHP.

Using stdClass Object

Another approach is to use of the stdClass object. By generating a PHP object of the stdClass, we may produce an array of objects. The PHP standard library of functions contains a definition for the stdClass. It is an empty class that can be used to typecast and set dynamic properties rather than being a base class for objects.

Here is an example of how to create an array of objects in PHP using the stdClass object:

This code will create an array of two objects, each of which has a name and age property. The resulting array will look something like this:

In this example, we create two stdClass objects and set their properties individually. Then, we add each object to an array using the [] syntax, which appends the new value to the end of the array. Finally, we use the print_r function to print the resulting array of objects.

That’s all about how to create array of Objects in PHP.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *