Home » PHP

PHP array_column() Function with Example

PHP array_column() function: Here, we are going to learn about the array_column() function with example in PHP.
Submitted by IncludeHelp, on February 07, 2019

PHP array_column() function

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:

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

Here,

  • 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.

It returns an array with keys (either integer index or other column’s name as index keys) & value.

Examples:

    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 code:

<?php
	$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",
		),		
	);
	
	//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] => Amit 
    [1] => Mohan
    [2] => Mohit
)
Array
(
    [101] => Gwalior
    [102] => New Delhi
    [103] => Chennai
)
Array
(
    [Amit] => Gwalior
    [Mohan] => New Delhi
    [Mohit] => Chennai
)






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.