How to push data object to array of object in php?

by raphael_tillman , in category: PHP General , 2 months ago

How to push data object to array of object in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , a month ago

@raphael_tillman 

To push a data object into an array of objects in PHP, you can follow these steps:

  1. Create a new object using the data you want to push.
  2. Add the new object to the array of objects.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Example data object
$data = [
    'name' => 'John',
    'age' => 25,
];

// Existing array of objects
$arrayOfObjects = [
    (object) ['name' => 'Alice', 'age' => 30],
    (object) ['name' => 'Bob', 'age' => 35],
];

// Create a new object using the data
$newObject = (object) $data;

// Push the new object into the array
$arrayOfObjects[] = $newObject;

// Print the updated array of objects
print_r($arrayOfObjects);


Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Array
(
    [0] => stdClass Object
        (
            [name] => Alice
            [age] => 30
        )

    [1] => stdClass Object
        (
            [name] => Bob
            [age] => 35
        )

    [2] => stdClass Object
        (
            [name] => John
            [age] => 25
        )
)


The [] syntax is used to push the new object into the array.