Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
In PHP, how can I add an object element to an array?
In PHP, you can add an object element to an array using several methods. The most common approach is to create an object and then append it to an array using the array push syntax.
Method 1: Using stdClass Object
Create a standard object and add it to an array ?
<?php
// Create an existing array
$myArray = ['a', 'c'];
// Create an object
$object = new stdClass();
$object->name = "My name";
// Add object to array
$myArray[] = $object;
// Display the array
print_r($myArray);
?>
Array
(
[0] => a
[1] => c
[2] => stdClass Object
(
[name] => My name
)
)
Method 2: Using Object Casting
You can also create an object directly using array-to-object casting ?
<?php
// Create an existing array
$myArray = ['a', 'c'];
// Add object using casting
$myArray[] = (object) ['name' => 'My name'];
// Display the array
print_r($myArray);
?>
Array
(
[0] => a
[1] => c
[2] => stdClass Object
(
[name] => My name
)
)
Method 3: Adding Multiple Objects
You can add multiple objects to an array in a loop ?
<?php
$myArray = [];
$names = ['John', 'Jane', 'Bob'];
foreach($names as $name) {
$object = new stdClass();
$object->name = $name;
$myArray[] = $object;
}
print_r($myArray);
?>
Array
(
[0] => stdClass Object
(
[name] => John
)
[1] => stdClass Object
(
[name] => Jane
)
[2] => stdClass Object
(
[name] => Bob
)
)
Conclusion
Adding objects to arrays in PHP is straightforward using the `[]` syntax. You can use `stdClass` objects or cast arrays to objects. Both methods append the object to the end of the array.
Advertisements
