PHP Array Function : array_column()

The array_column() function returns the values from a single column in the multidimensional array. The basic syntax is as follows :
 array_column(array, column_key, inedx_key);
Where array is name of the array, column_key is an integer key or a string key name of the column of values to return, and index_key is column to use as the index/keys for the returned array, and this is optional.

Example :
<?php

  $employees = array(
    array(
      "Name" => "John snow",
      "Age" => "35",
      "Salary" => "20000"
    ),
    array(
      "Name" => "Luci hunt",
      "Age" => "24",
      "Salary" => "15000"
    ),
    array(
      "Name" => "James bond",
      "Age" => "55",
      "Salary" => "75000"
    )
  );

  $new_arr = array_column($employees, "Name");

  $len = count($new_arr); // indexed array
  
  for($x = 0; $x < $len; $x++) {
    echo $new_arr[$x] . "<br/>";
  } 

?>
Output :

John snow
Luci hunt
James bond

Lets see another example :
<?php

  $employees = array(
    array(
      "Name" => "John snow",
      "Age" => "35",
      "Salary" => "20000"
    ),
    array(
      "Name" => "Luci hunt",
      "Age" => "24",
      "Salary" => "15000"
    ),
    array(
      "Name" => "James bond",
      "Age" => "55",
      "Salary" => "75000"
    )
  );

  $new_arr = array_column($employees, "Salary", "Name");

  foreach($new_arr as $key => $value) {
    echo $key . " : " . $value . "<br/>";
  }

?>
Output :

John snow : 20000
Luci hunt : 15000
James bond : 75000

Next Topic :