Computer >> Computer tutorials >  >> Programming >> PHP

In PHP, how can I add an object element to an array?


The code is as follows −

Example

$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;

Output

This will produce the following output −

Suppose myArray already contains ‘a’ and ‘c’, the value of “My name” will be added to it. It becomes
Array {
   a:0, c:1, “My name”:2
}

The object is created and then it is pushed to the end of the array (that was previously present).

Alternative

$myArray[] = (object) ['name' => 'My name'];