Home > Backend Development > PHP Tutorial > How Does PHP\'s array_column() Function Extract Columns of Object Properties?

How Does PHP\'s array_column() Function Extract Columns of Object Properties?

Barbara Streisand
Release: 2024-10-20 08:59:02
Original
344 people have browsed it

How Does PHP's array_column() Function Extract Columns of Object Properties?

Retrieving Object Property Arrays in PHP

When dealing with arrays of objects, it can be necessary to extract specific columns of properties for further processing. This article explores a concise method for extracting these columns in a single line using the array_column() function.

Array of Objects

Consider the following array of cat objects:

<code class="php">$cats = [
    (object)['id' => 15],
    (object)['id' => 18],
    (object)['id' => 23]
];</code>
Copy after login

array_column() Function

To extract the column of IDs from these objects, we can leverage the array_column() function. Introduced in PHP 7.0, this function provides a convenient way to retrieve columns of properties from arrays of objects or arrays.

Usage

To use array_column(), we specify the input array as the first parameter and the desired property name as the second parameter. For instance, to extract the IDs from our $cats array, we would use:

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

The result would be an array containing the IDs of the cats:

<code class="php">[15, 18, 23]</code>
Copy after login

Note for PHP Versions Prior to 7.0

If you are using PHP versions prior to 7.0, array_column() is not available. Alternative approaches such as array_walk() or a custom function can be used for property extraction.

The above is the detailed content of How Does PHP\'s array_column() Function Extract Columns of Object Properties?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template