DEV Community

Cover image for Uses of array_column function PHP
Istiaq Nirab
Istiaq Nirab

Posted on

Uses of array_column function PHP

PHP has a build function called array_column ()

Using this function a new array be created with the values of a certain key in a multi-dimension array.

The function has 5 parameters & 2 are mandatory to use.

  • input : Take value from the multidimensional array.
  • column_key : The value of the key for the index.
  • index_key : If you want to give a key to the index as a new array key. It is not mandatory to use it.

Example

<?php

$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
print_r($first_names);

?>
Enter fullscreen mode Exit fullscreen mode

Result

Array (
 [0] => John     
 [1] => Sally     
 [2] => Jane     
 [3] => Peter 
)
Enter fullscreen mode Exit fullscreen mode

Another example Using the index key,

Example

<?php

$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);

?>
Enter fullscreen mode Exit fullscreen mode

Result

Array (     
 [2135] => Doe     
 [3245] => Smith     
 [5342] => Jones     
 [5623] => Doe 
)
Enter fullscreen mode Exit fullscreen mode

Source Link :

https://www.php.net/manual/en/function.array-column.php

Thanks .

Top comments (1)

Collapse
 
muhammadmp profile image
Muhammad MP

Amazing.