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

Viewed 86746

Here is a weird question. I am building an array of objects manually, like this:

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

$pages_array[1]->slug = "a";
$pages_array[1]->title = "100% Wide (Layout A)";
$pages_array[1]->template = "interior";

$pages_array[2]->slug = "homepage";
$pages_array[2]->title = "Homepage";
$pages_array[2]->template = "homepage";

I like how clearcut this is, but because I have to specify the index number, I can't rearrange them easily. How can I do this without the index number? Related, what is a better way to do this?

I also tried writing this by making a class, and having each spot on the array be instances of that class. But since this is a configuration file, it was hard to read and know what argument went with what parameter. That's why I chose this old-school method above.

Any thoughts are much appreciated!

6 Answers

There are three ways:

Way 1 :

$pages_array=[
    [
        "id" => 1,
        "name" => "James"
    ],
    [
        "id" => 2,
        "name" => "Mary"
    ]

];

Way 2 :

 $pages_array[0] =
    [
        "id" => 1,
        "name" => "James"
    ];
 $pages_array[1] = 
    [
        "id" => 2,
        "name" => "Mary"
    ];

Way 3 :

$pages_array = array(
    array(
      "id" => 2,
      "name" => "Mary"
    ),

    array(
      "id" => 1,
      "name" => "James"
    ),
   
);
Related