Header Ads Widget

Responsive Advertisement

Ticker

6/recent/ticker-posts

Function array_column() in PHP

 PHP array_column() Function

It is an inbuilt function in PHP. The array_column() function is used to return the values from a single column in the input array.
The function returns an array that contains the values from the single column of an input array, identified by column_number.
Optionally, the index_key may also be provided to index the values in the returned array by the values from an index_key column of an input array.

Syntax:

array_column ( array $input_array, mixed $column_key [, mixed $index_key = NULL ] )

Out of the three parameters, two are mandatory and one is optional. Let’s look at the parameters.

Parameters:

  • $input_array (mandatory): This parameter refers to the original multi-dimensional array from which we want to extract all the values of a particular column.
  • $column_key (mandatory): This parameter refers to the column of values that is needed to be returned. This value may be an integer key of the column, or it may be a string key name for an associative array or property name. It may also be NULL to return complete arrays or objects.
  • $index_key (optional): This is an optional parameter and refers to the column to use as the index/keys for the returned array in output. This value may be the integer key of the column, or it may be the string key name.

Example 1:

<?php
$users = array(
array('id' => 1, "firstname" => "nikunj", "lastname" => "joshi", "country"=> "india" ),
array('id' => 2,"firstname"=> "jay", "lastname" => "joshi", "country"=> "london" ),
array('id' => 3,"firstname"=> "smith", "lastname" => "jones", "country"=> "united states" ),
array('id' => 4,"firstname"=> "peter", "lastname" => "doe", "country"=> "united states" )
);
$name_arr = array_column($users, 'firstname');
print_r($name_arr);

Output:

The above example will output:

Array
(
[0] => nikunj
[1] => jay
[2] => smith
[3] => peter
)


Example 2:
<?php
$users = array(
array('id' => 1, "firstname" => "nikunj", "lastname" => "joshi", "country"=> "india" ),
array('id' => 2,"firstname"=> "jay", "lastname" => "joshi", "country"=> "london" ),
array('id' => 3,"firstname"=> "smith", "lastname" => "jones", "country"=> "united states" ),
array('id' => 4,"firstname"=> "peter", "lastname" => "doe", "country"=> "united states" )
);
$id_name_arr = array_column($users, 'firstname', 'id');
print_r($id_name_arr);


Output:

The above example will output:

Array
(
[1] => nikunj
[2] => jay
[3] => smith
[4] => peter
)

If you have any query or suggestions, feel free to ask me via the comment section below.

must watch some other topics :

cake PHP training institute
cake PHP training course
cake php training online

Post a Comment

0 Comments