
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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 −
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]
- Related Articles
- Extract unique objects by attribute from an array of objects in JavaScript
- Extract arrays separately from array of Objects in JavaScript
- Retrieve property value selectively from array of objects in JavaScript
- Sorting an array of objects by property values - JavaScript
- Search from an array of objects via array of string to get array of objects in JavaScript
- Extract unique values from an array - JavaScript
- Filter array of objects by a specific property in JavaScript?
- Pull multiple objects from an array in MongoDB?
- Sorting an array objects by property having null value in JavaScript
- Set object property in an array true/false, whether the id matches with any id from another array of objects in JavaScript?
- JavaScript Count the number of unique elements in an array of objects by an object property?
- PHP Call methods of objects in array using array_map?
- How to create an array of partial objects from another array in JavaScript?
- Sum of array object property values in new array of objects in JavaScript
- Removing duplicate elements from an array in PHP

Advertisements