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

If you make them arrays with named keys rather than objects, you can do it like this:

$pages_array = array(
     array(
         'slug' => 'index',
         'title' => 'Site Index',
         'template' => 'interior'
     ),

     array(
         'slug' => 'a',
         'title' => '100% Wide (Layout A)',
         'template' => 'interior'
     ),

     array(
         'slug' => 'homepage',
         'title' => 'Homepage',
         'template' => 'homepage'
     )
);

You can combine this with Fanis' solution and use the slugs as the keys if you like.


This code

 $pages_array[1]->slug = "a";

is invalid anyways - you'll get a "strict" warning if you don't initialize the object properly. So you have to construct an object somehow - either with a constructor:

 $pages_array[] = new MyObject('index', 'title'....)

or using a stdclass cast

 $pages_array[] = (object) array('slug' => 'xxx', 'title' => 'etc')

Tags:

Php

Arrays

Object