Extract a property from an array of objects in PHP

PHPServer Side ProgrammingProgramming

Given the below code, the task is to extract the ID of the my_object variable −

Example

$my_object = Array
( [0] => stdClass Object
   (
      [id] => 12
   ),
   [1] => stdClass Object
   (
      [id] => 33
   ),
   [2] => 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');

Output

This will produce the following output −

[12, 33, 59]
raja
Published on 06-Apr-2020 07:32:30
Advertisements