How to push objects in php?

by lindsey.homenick , in category: PHP General , 10 months ago

How to push objects in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 10 months ago

@lindsey.homenick 

In PHP, you can push objects to an array using the array_push() function or by directly assigning the object to a specific index of the array.


Here's an example using array_push():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Creating an array
$myArray = array();

// Creating an object
$myObject = new stdClass();
$myObject->name = "John";
$myObject->age = 25;

// Pushing the object into the array
array_push($myArray, $myObject);


Alternatively, you can directly assign the object to a specific index of the array:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Creating an array
$myArray = array();

// Creating an object
$myObject = new stdClass();
$myObject->name = "John";
$myObject->age = 25;

// Assigning the object to a specific index of the array
$myArray[] = $myObject;


Both methods achieve the same result of pushing the object into the array.