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
Extract a property from an array of objects in PHP
In PHP, you can extract a specific property from an array of objects using several methods. This is useful when you need to get all values of a particular property from multiple objects.
Sample Data
Let's start with an array of objects containing ID properties −
<?php
$my_object = array(
(object) ['id' => 12],
(object) ['id' => 33],
(object) ['id' => 59]
);
print_r($my_object);
?>
Array
(
[0] => stdClass Object
(
[id] => 12
)
[1] => stdClass Object
(
[id] => 33
)
[2] => stdClass Object
(
[id] => 59
)
)
Using array_column() (PHP 5.5+)
The array_column() function is the most efficient method for extracting a property −
<?php
$my_object = array(
(object) ['id' => 12],
(object) ['id' => 33],
(object) ['id' => 59]
);
$object_id = array_column($my_object, 'id');
print_r($object_id);
?>
Array
(
[0] => 12
[1] => 33
[2] => 59
)
Using array_map() with Anonymous Function
For more complex extraction logic, use array_map() with an anonymous function −
<?php
$my_object = array(
(object) ['id' => 12],
(object) ['id' => 33],
(object) ['id' => 59]
);
$object_id = array_map(function($obj) {
return $obj->id;
}, $my_object);
print_r($object_id);
?>
Array
(
[0] => 12
[1] => 33
[2] => 59
)
Using foreach Loop
A traditional approach using a foreach loop for maximum control −
<?php
$my_object = array(
(object) ['id' => 12],
(object) ['id' => 33],
(object) ['id' => 59]
);
$object_id = array();
foreach ($my_object as $obj) {
$object_id[] = $obj->id;
}
print_r($object_id);
?>
Array
(
[0] => 12
[1] => 33
[2] => 59
)
Comparison
| Method | PHP Version | Performance | Flexibility |
|---|---|---|---|
array_column() |
5.5+ | Fastest | Basic |
array_map() |
All | Good | High |
foreach |
All | Good | Maximum |
Conclusion
Use array_column() for simple property extraction as it's the most efficient. For complex logic or older PHP versions, use array_map() or foreach loops.
Advertisements
