PHP array_column() Function with Example

PHP array_column() work: Here, we will find out about the array_column() work with example in PHP.

PHP array_column() work

array_column() work is a cluster work, it is utilized to get the value from a solitary segment of given single-dimensional, different dimensional exhibits, object and so forth. By utilizing this capacity, we can likewise indicate the other section’s value as the “keys” of the new returned cluster.

Syntax:

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

Here,

  • array_name is an info cluster/fundamental exhibit from where we need to separate the section’s value.
  • column_name is the name of the segment of the information cluster.
  • index_key is a discretionary parameter, it is utilized to characterize the values of another segment as list enters in a returned cluster.

It restores an exhibit with keys (either integer record or other section’s name as file keys) and value.

Example:

    Input:
	    $employee = array(
		    array(
			    'emp_id' => 101,
			    'name' => "Kishan",
			    'city' => "Bilaspur",
		    ),
		    array(
			    'emp_id' => 102,
			    'name' => "Durgesh",
			    'city' => "Raipur",
		    ),
		    array(
			    'emp_id' => 103,
			    'name' => "Aakash",
			    'city' => "Bhopal",
		    ),		
	    );

    Function call: array_column($employee, 'name');
    Output:
    Array
    (
        [0] => Kishan
        [1] => Durgesh
        [2] => Mohit
    )

PHP Code:

<?php
	$employee = array(
		array(
			'emp_id' => 101,
			'name' => "Kishan",
			'city' => "Bilaspur",
		),
		array(
			'emp_id' => 102,
			'name' => "Durgesh",
			'city' => "Raipur",
		),
		array(
			'emp_id' => 103,
			'name' => "Aakash",
			'city' => "Bhopal",
		),		
	);
	
	//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:

Array
(
    [0] => Kishan
    [1] => Durgesh
    [2] => Mohit
)
Array
(
    [101] => Bilaspur
    [102] => Raipur
    [103] => Bhopal
)
Array
(
    [Kishan] => Bilaspur
    [Durgesh] => Raipur
    [Mohit] => Bhopal
)

Leave a Comment

error: Alert: Content is protected!!