90

So I have been searching for a while and cannot find the answer to a simple question. Is it possible to have an array of objects in PHP? Such as:

$ar=array();    
$ar[]=$Obj1    
$ar[]=$obj2

For some reason I have not been able to find the answer anywhere. I assume it is possible but I just need to make sure.

1
  • 3
    Why not try it out and see what happens? Do you have any specific question about this? Commented May 22, 2024 at 6:11

8 Answers 8

140

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
    public $color;
    public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
    echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}
Sign up to request clarification or add additional context in comments.

5 Comments

I've tried the php site and haven't been able to find anything. I am also sitting with the book "PHP Objects, Patters, and Practice" by Matt Zandstra. and haven't been able to find any information.
Question: Suppose that you wanted to just print the color of just one Car in that array. Would you say echo $cars[0]->color; to print the first one, and echo $cars[1]->color; to print the second one?
I just remembered that there is this great thing called Ideone, which lets you test out code snippets online. To answer my own question: yes, you can: ideone.com/8XB4TC
@MikeWarren: Correct, therein lies the power of hydrating an array of objects, aka as a 'collection'. You could also be specific about the keys each object gets, in case you need to retrieve specific objects within a collection, for example `$car['blue_4_door'] = $anotherCar'.
So if I have a 20 objects, I have to type 20 times $yourCar = new Car(); ? There is not some more elegant way to do that as in JS like let car = [{}, {},{}] ?
31

Yes.

$array[] = new stdClass;
$array[] = new stdClass;

print_r($array);

Results in:

Array
(
    [0] => stdClass Object
        (
        )

    [1] => stdClass Object
        (
        )

)

5 Comments

I timed it and this took twenty seconds to test, including typing time.
So would my class name replace stdClass? What if the object is already created and you wanted to just add it to the array. Can use constructors with the method above? p.s. sorry I am new to SO
There's nothing special about it. Add it to the array however you like. This is simply a demonstration that you can very, very easily test these kinds of things out yourself.
This is the answer to the question, while the accepted answer points towards an entirely different direction of OOPS
@ceejayoz Yes, but it takes less than 5 seconds to Google this answer ;)
20

You can do something like this:

$posts = array(
  (object) [
    'title' => 'title 1',
    'color' => 'green'
  ],
  (object) [
    'title' => 'title 2',
    'color' => 'yellow'
   ],
   (object) [
     'title' => 'title 3',
     'color' => 'red'
   ]
);

// Then you can access it like this: $posts[0]->title  

Result:

var_dump($posts);

array(3) {
  [0]=>
  object(stdClass)#1 (2) {
    ["title"]=>
    string(7) "title 1"
    ["color"]=>
    string(5) "green"
  }
  [1]=>
  object(stdClass)#2 (2) {
    ["title"]=>
    string(7) "title 2"
    ["color"]=>
    string(6) "yellow"
  }
  [2]=>
  object(stdClass)#3 (2) {
    ["title"]=>
    string(7) "title 3"
    ["color"]=>
    string(3) "red"
  }
}

Comments

12

Yes, its possible to have array of objects in PHP.

class MyObject {
  private $property;

  public function  __construct($property) {
    $this->Property = $property;
  }
}
$ListOfObjects[] = new myObject(1); 
$ListOfObjects[] = new myObject(2); 
$ListOfObjects[] = new myObject(3); 
$ListOfObjects[] = new myObject(4); 

print "<pre>";
print_r($ListOfObjects);
print "</pre>";

2 Comments

Do we have to go on incrementing the constructor index in myObject() each time we want to add a new object in the array or is it optional? All this OOP stuff in web languages is simply OOPS!
@YoustayIgo that's just for the example, so that the output distinguishes the objects from each other. You can put whatever value you like in the constructor, it then simply assigns that value to the object's $property property.
8

Arrays can hold pointers so when I want an array of objects I do that.

$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);

This will show that the object is referenced and accessible through the array.

Comments

5

Another intuitive solution could be:

class Post
{
    public $title;
    public $date;
}

$posts = array();

$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';

$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';

foreach ($posts as $post) {
  echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}

1 Comment

THE BEST ... saved me a lot of time. A small tweak here though, instead of doing this increment just try to put it inside a loop and use a variable for increment. doesn't matter if it's for a single or hundreds of objects and it will look more generic solution.
2

First of all create 2d array

$posts = array(
  [
    'title' => 'title 1',
  ],
  [
    'title' => 'title 2',
  ],
  [
     'title' => 'title 3',
  ]
);

$result = json_decode(json_encode($posts));

The result will return an array of objects.

Comments

-1

Although all the answers given are correct, in fact they do not completely answer the question which was about using the [] construct and more generally filling the array with objects.

A more relevant answer can be found in how to build arrays of objects in PHP without specifying an index number? which clearly shows how to solve the problem.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.