Home >Backend Development >PHP Tutorial >How to Extract Cat IDs from Array of Objects in PHP Using array_column() Function?
When dealing with an array of objects, such as an array of cat objects, extracting a specific property can often be a necessary task. In this particular case, we aim to extract the id property of each cat object into a new array.
One approach, as suggested in your question, involves using array_walk() with create_function. While this method is certainly feasible, a more elegant and efficient solution exists.
Introduced in PHP 7.0, the array_column() function provides a straightforward way to extract a specific property from an array of objects. The syntax is as follows:
<code class="php">array_column(array $input, string $column_key, string $index_key = null): array</code>
In our case, we can use array_column() to extract the id property from the $cats array:
<code class="php">$catIds = array_column($cats, 'id');</code>
The $catIds variable will now contain an array of cat IDs, making it easy to access and manipulate these values as needed.
It's important to note that, as mentioned in the problem answer, the array_column() function requires the source array to be an array or convertible to an array. If your $cats array is not an array, you will need to convert it first by using, for example, the get_object_vars() function.
With this method, you can easily and efficiently extract a column of properties from an array of objects, streamlining your PHP development tasks.
The above is the detailed content of How to Extract Cat IDs from Array of Objects in PHP Using array_column() Function?. For more information, please follow other related articles on the PHP Chinese website!