Create PHP Array of Objects: 5 Code Examples in 2023

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Create an Array of Objects in PHP

There are 2 steps to creating arrays of objects in PHP.

You will want first to initialize an empty array. Once complete, you should pass that reference to any object creation function. Create your object and attach it as a new reference to your PHP array.

Creating Array of Objects PHP Code Example

//Initialize an array.
$employees = array();
 
//Add objects
$employees[0] = new Employee("Steve Hans", "111-222-333", "60,000");
$employees[1] = new Employee("Raymond Rize", "112-212-313", "80,000");
$employees[2] = new Employee("Sams Brian", "122-213-713", "70,000");

PHP is both a procedural & object-oriented programming language, and this article overviews the basics. Stay with us till the end to learn more.

Relevant Content: Classes & Objects

Classes and objects are at the core of object-oriented programming (OOP).

Objects contain data in attributes and code in methods. They are based on an underlying template, a class. Think of a class as a blueprint for an object.

You can create as many objects as you want based on the template.

A useful analogy will be a blueprint for a vehicle and an actual vehicle based on that. The blueprint defines the properties and specifications of the car. The vehicle itself is a realization of that plan. Sounds philosophical!

Let’s try another example, much simpler.

Here is a Circle class with attributes as follows:

  • Color
  • Radius

And some methods.

  • Rotate
  • getRadius
  • getArea

To the left are the objects of this class.

They all have the same attributes, but each with a different value. All of them can rotate and return their radius and area information. These sets of methods are defined in their class.

Object Oriented Programming is a vast programming paradigm with alot of other ideas and concepts, but almost all of them are tied to these two fundamental entities: classes & objects.

Click here to read our intro to Object-Oriented PHP Programming article

The rest of the text will make sense if the idea of classes and objects is clear. Make sure to think and conceptualize how both entities fit in a wider scope.

Scenario: Create PHP Array of Objects with Employee Class

Background and Setup: Array of Employee Objects in PHP

The following is an example of a class in PHP. 

class Employee {
 
   //attributes
   private $name;
   private $socialSecurityNumber;
   private $baseSalary;
  
   //constructor function
   function __construct($name, $socialSecuirtyNumber, $baseSalary)  {
       $this->name = $name;
       $this->socialSecurityNumber = $socialSecuirtyNumber;
       $this->baseSalary = $baseSalary;
   }
 
   //Getter functions
   function get_name() {
       return $this->name;
   }
 
   function get_ssn() {
       return $this->socialSecurityNumber;
   }
 
   function get_salary() {
       return $this->baseSalary;
   }
 
   //Setter functions
   function set_name($name) {
       $this->name = $name;
   }
 
   function set_ssn($ssn) {
       $this->socialSecurityNumber = $ssn;
   }
 
   function set_salary($salary) {
       $this->baseSalary = $salary;
   }
 
   function to_string()
   {
       return "Employee Name: {$this->get_name()}\nSSN: {$this->get_ssn()}\nBase Salary: {$this->get_salary()}\n\n";
   }
 
}

Let’s break down the syntax and understand every bit. 


We define a class by a class keyword followed by the className.

class Employee {
  //attributes and methods go here.
}

Attributes are properties of a class. The Employee class has the following private attributes. The keyword private is an access modifier that determines the scope of access to these attributes.

class Employee {
 
   //attributes
   private $name;
   private $socialSecurityNumber;
   private $baseSalary;
 }

Constructor functions are essential for building objects.

Every class has a default constructor. Overriding a constructor means adding some initial logic, for instance, instantiating attributes with user-supplied values.

lass Employee {
 
   //attributes
   private $name;
   private $socialSecurityNumber;
   private $baseSalary;
  
   //constructor function
   function __construct($name, $socialSecuirtyNumber, $baseSalary)  {
       $this->name = $name;
       $this->socialSecurityNumber = $socialSecuirtyNumber;
       $this->baseSalary = $baseSalary;
   }
}

Remember, a class includes methods too.

This class includes getter and setter methods. These methods help retrieve or assign attribute values. Finally, this class has a method to return employee information.

class Employee {
 
   //attributes
   private $name;
   private $socialSecurityNumber;
   private $baseSalary;
  
   //constructor function
   function __construct($name, $socialSecuirtyNumber, $baseSalary)  {
       $this->name = $name;
       $this->socialSecurityNumber = $socialSecuirtyNumber;
       $this->baseSalary = $baseSalary;
   }
 
   //Getter functions
   function get_name() {
       return $this->name;
   }
 
   function get_ssn() {
       return $this->socialSecurityNumber;
   }
 
   function get_salary() {
       return $this->baseSalary;
   }
 
   //Setter functions
   function set_name($name) {
       $this->name = $name;
   }
 
   function set_ssn($ssn) {
       $this->socialSecurityNumber = $ssn;
   }
 
   function set_salary($salary) {
       $this->baseSalary = $salary;
   }
 
   function to_string()
   {
       return "Employee Name: {$this->get_name()}\nSSN:     {$this->get_ssn()}\nBase Salary: {$this->get_salary()}\n\n";
   }
 
}

Cool! Now let’s see how to create an array of objects in PHP. Before that, let’s learn to create one object.

$employee_1 = new Employee("Steve Hans", "111-222-333", "60,000");

Let’s call the to_string( ) method of this object.

echo $employee_1->to_string();
 
/*
OUTPUT
Employee Name: Steve Hans
SSN: 111-222-333
Base Salary: 60,000
*/

Voila! Let’s see how to make an array of objects in PHP.

How to Create an Array of Objects in PHP using array() function

First things first, let’s initialize an array. Following the array creation, the next step adds employee objects to the array by index.

Here’s an example.

//Initialize an array.
$employees = array();
 
//Add objects
$employees[0] = new Employee("Steve Hans", "111-222-333", "60,000");
$employees[1] = new Employee("Raymond Rize", "112-212-313", "80,000");
$employees[2] = new Employee("Sams Brian", "122-213-713", "70,000");

Let’s make it more fun and call to_string() on every object in the array.

foreach($employees as $employee) {
   echo $employee ->  to_string();
}

The output is as follows.

Employee Name: Steve Hans
SSN: 111-222-333
Base Salary: 60,000

Employee Name: Raymond Rize
SSN: 112-212-313
Base Salary: 80,000

Employee Name: Sams Brian
SSN: 122-213-713
Base Salary: 70,000

Option2: How to Create an Array of Objects in PHP using array_push() function

PHP array_push function appends values to an array. The following example uses this function to add employee objects to the array.

//Initialize an array.
$employees = [];
 
//Add objects
array_push($employees, new Employee("Steve Hans", "111-222-333", "60,000"));
array_push($employees, new Employee("Raymond Rize", "112-212-313", "80,000"));
array_push($employees, new Employee("Sams Brian", "122-213-713", "70,000"));

There is another way to append to an array of objects in PHP.

//Initialize an array.
$employees = [];
 
//Add objects
$employees[] = new Employee("Steve Hans", "111-222-333", "60,000");
$employees[] = new Employee("Raymond Rize", "112-212-313", "80,000");
$employees[] = new Employee("Sams Brian", "122-213-713", "70,000");

Great! Let’s jump to a conclusion and wrap up the article.

Creating Array of Objects in PHP

This article explores how to create an array of objects in PHP.

The article starts with a solid overview of OOP fundamentals – class & object. After the overview section, the article defines an employee class in PHP and explains the syntax in depth.

Finally, the article jumps to the main subject and shows examples of how to declare an array of objects in PHP. So, that’s all for this article.

Stay tuned at FuelingPHP to learn more.

Classes and Functions Mentioned

array: (PHP 4, 5, 7, 8) A core PHP function that creates an array in PHP. The function came in PHP 4 and remains stable til now and seems to stay stable in future.

array_push : (PHP 4, 5, 7, 8) A core PHP function that adds one or more elements to an array. This function has been available from PHP 4 up to the latest PHP. Given the stability and utility, this function seems to remain stable in the future.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.