PHP Array array_column() Function (With Examples)

In this tutorial, we will learn about the PHP array_column() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_column() function

The array_column() function is an array function, it is used to get the value from a single column of given single dimensional, multiple dimensional arrays, object etc. By using this function, we can also specify the other column's value as the "keys" of the new returned array.

Syntax

The syntax of the array_column() function:

array_column(array_name, column_name, [index_key]) : array

Parameters

The parameters of the array_column() function:

  • array_name is an input array/main array from where we have to extract the column's value.
  • column_name is the name of the column of the input array.
  • index_key is an optional parameter, it is used to define the values of another column as index keys in a returned array.

Return Value

The return type of this method is array, it returns an array with keys (either integer index or other column’s name as index keys) & value.

Sample Input/Output

Input:
$employee = array(
    array(
        'emp_id' => 101,
        'name' => "Amit",
        'city' => "Gwalior",
    ),
    array(
        'emp_id' => 102,
        'name' => "Mohan",
        'city' => "New Delhi",
    ),
    array(
        'emp_id' => 103,
        'name' => "Mohit",
        'city' => "Chennai",
    ),
);

Function call:
array_column($employee, 'name');

Output:
Array
(
    [0] => Amit 
    [1] => Mohan
    [2] => Mohit
)

PHP array_column() Function Example

<?php
$employee = array(
    [
        "emp_id" => 101,
        "name" => "Amit",
        "city" => "Gwalior",
    ],
    [
        "emp_id" => 102,
        "name" => "Mohan",
        "city" => "New Delhi",
    ],
    [
        "emp_id" => 103,
        "name" => "Mohit",
        "city" => "Chennai",
    ],
);

//Extracting the values of "name"
$arr1 = array_column($employee, "name");
print_r($arr1);

//Extracting city with index key as "emp_id"
$arr1 = array_column($employee, "city", "emp_id");
print_r($arr1);

//Extracting name with index key as "name"
$arr1 = array_column($employee, "city", "name");
print_r($arr1);
?>

Output

The output of the above example is:

Array
(
    [0] => Amit 
    [1] => Mohan
    [2] => Mohit
)
Array
(
    [101] => Gwalior
    [102] => New Delhi
    [103] => Chennai
)
Array
(
    [Amit] => Gwalior
    [Mohan] => New Delhi
    [Mohit] => Chennai
)

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.