Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Extract Property from an Array of Objects in PHP



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]
Updated on: 2020-04-06T07:34:36+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements