Home  >  Article  >  Backend Development  >  How to Extract a Column of Properties from an Array of Objects in PHP?

How to Extract a Column of Properties from an Array of Objects in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 09:02:30483browse

How to Extract a Column of Properties from an Array of Objects in PHP?

PHP: Efficiently Extract a Column of Properties from an Array of Objects

Many programming scenarios involve working with arrays of objects, where each object may have multiple properties. Occasionally, it becomes necessary to extract a specific property from each object to form a separate array. In PHP, achieving this goal in a single line, without resorting to loops or external functions, can be tricky.

One potential approach is utilizing the array_walk() function along with create_function. However, a more straightforward and elegant solution is available in PHP 7.0 and later.

array_column() to the Rescue

The array_column() function was introduced in PHP 7.0 and allows you to extract a specific column of data from an array of arrays or arrays of objects. Simply pass in your array of objects as the first parameter and the name of the desired property as the second parameter:

<code class="php">$idCats = array_column($cats, 'id');</code>

In this example, the $idCats variable will now contain an array of the IDs of all the cats objects.

Note for PHP Versions Prior to 7.0

If you are using a PHP version earlier than 7.0, you can still use the array_map() function:

<code class="php">$idCats = array_map(function($cat) { return $cat->id; }, $cats);</code>

While this method is slightly more verbose, it achieves the same result.

By leveraging array_column() or array_map(), you can efficiently extract a column of properties from an array of objects in PHP, enabling you to streamline your code and improve performance.

The above is the detailed content of How to Extract a Column of Properties from an Array of Objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn