how to build arrays of objects in PHP without specifying an index number?

how to build arrays of objects in PHP without specifying an index number?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Building Arrays of Objects Without Hardcoded Indices

The pattern shown in your example relies on a specific quirk of how PHP handles array keys. When you initialize an array using [], PHP creates sparse arrays if you skip indices, but it also assigns numeric keys based on the order of assignment. However, simply omitting the index entirely while assigning properties to existing object references requires that those objects already exist in the collection.

To build a collection where you can rearrange items easily without specifying an index number during assignment, you must shift your mental model from "assigning to position N" to "associating data with a unique identity."

The Identity vs. Position Problem

Your current approach:

$pages_array[0]->slug = "index";
$pages_array[1]->title = "Site Index";

This couples the data to its position. If you want to move the "Homepage" template from index 2 to index 0, you have to physically reorder the array or write complex conditional logic to swap values. This is brittle.

The solution is to define objects using a unique key rather than an integer index. In PHP, this is done via associative arrays. Instead of $pages_array[0], you use something like $pages_array['page_id'].

Using Associative Arrays for Reordering

If you strictly need to avoid specifying an index number in the sense of not knowing which "slot" holds which data, you can generate unique keys automatically or use descriptive string keys.

Here is how you might refactor your example using automatic numeric keys that are derived from a counter, ensuring no gaps exist but maintaining association:

$pages = [];
$i = 0;

// Define the first page
$page = new stdClass();
$page->slug = "index";
$page->title = "Site Index";
$page->template = "interior";
$pages[$i++] = $page;

// Define the second page
$page = new stdClass();
$page->slug = "a";
$page->title = "100% Wide (Layout A)";
$page->template = "interior";
$pages[$i++] = $page;

// Define the third page
$page = new stdClass();
$page->slug = "homepage";
$page->title = "Homepage";
$page->template = "homepage";
$pages[$i++] = $page;

In this pattern, you are not specifying which index the object belongs to (like [0] or [2]), but rather appending to the collection. The key is the current length of the array (count($pages)), which PHP calculates automatically. To access them later, you simply iterate: foreach ($pages as $page). This decouples your assignment logic from your retrieval logic.

The Data Class Alternative

You mentioned trying classes and finding it hard to read in a configuration context. This is a common friction point when mixing domain objects with flat configuration files. If the "configuration file" is actually just a script or an array definition within your application, using a dedicated class for the object structure is often superior to stdClass.

Consider defining a Page class:

class Page {
    public string $slug;
    public string $title;
    public string $template;

    public function __construct(string $slug, string $title, string $template) {
        $this->slug = $slug;
        $this->title = $title;
        $this->template = $template;
    }
}

Now your collection becomes:

$pages = [
    new Page('index', 'Site Index', 'interior'),
    new Page('a', '100% Wide (Layout A)', 'interior'),
    new Page('homepage', 'Homepage', 'homepage'),
];

This approach eliminates the need for index numbers entirely. You are constructing instances based on data, not positions. It also solves your readability issue: the constructor arguments define the parameters clearly, removing ambiguity about what goes where. If you truly need a config file format that maps to these objects, you can use a simple JSON or PHP array of associative arrays and instantiate the class in a single pass using array_map:

$config = [
    ['slug' => 'index', 'title' => 'Site Index', 'template' => 'interior'],
    ['slug' => 'a', 'title' => '100% Wide (Layout A)', 'template' => 'interior'],
];

$pages = array_map(function($data) {
    return new Page($data['slug'], $data['title'], $data['template']);
}, $config);

When to Use Which Approach

If you are building a configuration file for a framework or a complex application, the class-based approach is generally more robust. It enforces type safety and makes refactoring easier; if you need to add a meta property to all pages, you change one place.

However, if you prefer the "old-school" manual assignment because it feels less abstract for your specific team or workflow, simply switch from numeric indices to appending via a counter. This preserves the readability of direct assignment while removing the dependency on a specific index number being hardcoded in the logic.

For larger projects where maintainability is paramount, frameworks like Laravel handle object collection and instantiation patterns more explicitly through Service Providers or Factories, often abstracting away the manual array construction entirely. If you are working within the Laravel ecosystem, leveraging Eloquent collections or factory methods ensures that your "array of objects" remains consistent even as the underlying data structure evolves.

Our network