- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract a property from an array of objects in PHP
Given the below code, the task is to extract the ID of the my_object variable −
$my_object = Array (  => stdClass Object ( [id] => 12 ),  => stdClass Object ( [id] => 33 ),  => stdClass Object ( [id] => 59 ) )
The array_map function can be used for older versions of PHP. Below is a demonstration of the same.
$object_id = array_map(create_function('$o', 'return $o->id;'), $objects);
For PHP version 5.5 or higher, the array_column function could be used. Below is a demonstration of the same −
$object_id = array_column($my_object, 'id');
This will produce the following output −
[12, 33, 59]
- Pull multiple objects from an array in MongoDB?
- PHP Call methods of objects in array using array_map?