HOWTO · PHP
How to Create Array of Objects in PHP
This article introduces how to create an array of objects in PHP
On this page
PHP arrays can hold objects. You can group instances of a class with array(), store stdClass instances at numeric indexes, or add class instances to an array by index. In each case, the array index identifies an object, while properties such as name and type belong to that object.
The examples are provided as code illustrations without captured runtime output; each print_r() call lets you inspect the array and its objects when you run it.
Create an Array of Class Objects in PHP
Define a class, create its objects, and pass those objects to array(). In this example, each Motorcycle has public name and type properties. The resulting $bikes array has two entries at indexes 0 and 1.
<?php
class Motorcycle
{
public $name;
public $type;
}
$bike1 = new Motorcycle();
$bike1->name = 'Husqvarna';
$bike1->type = 'dirt';
$bike2 = new Motorcycle();
$bike2->name = 'Goldwing';
$bike2->type = 'touring';
$bikes = array($bike1, $bike2);
print_r($bikes);
print_r() shows the array indexes and then each object’s properties. The name and type values are not top-level array keys; they are properties on the Motorcycle objects at indexes 0 and 1.
Create an Array of stdClass Objects in PHP
PHP’s stdClass is a general-purpose class whose instances can have properties assigned to them. An instance is an object, not an array. Store each instance in the $bikes array, then set name and type on the object at that index:
<?php
$bikes = array();
$bikes[0] = new stdClass();
$bikes[0]->name = 'Husqvarna';
$bikes[0]->type = 'dirt';
$bikes[1] = new stdClass();
$bikes[1]->name = 'Goldwing';
$bikes[1]->type = 'touring';
print_r($bikes);
Here, $bikes[0] and $bikes[1] are the objects; name and type are properties assigned to each one. This is useful when a small object is enough and you do not need to define a named class.
Create an Array of Objects Using the array() Function in PHP
You can also initialize $bikes as an empty array and add Motorcycle objects afterward. This reverses the construction order from the first example: create the array first, then assign a new object to each index and set that object’s properties.
<?php
class Motorcycle
{
public $name;
public $type;
}
$bikes = array();
$bikes[0] = new Motorcycle();
$bikes[0]->name = 'Husqvarna';
$bikes[0]->type = 'dirt';
$bikes[1] = new Motorcycle();
$bikes[1]->name = 'Goldwing';
$bikes[1]->type = 'touring';
print_r($bikes);
Use this form when you want to build the array entry by entry, such as while processing input. Both class-based approaches produce an array whose numeric indexes point to objects; the properties remain part of each object.