Hi Reader's,
Welcome to FindNerd, today we are going to discuss how to get particular column of a multidimensional array using foreach loop in PHP?
Let have an array with full of key values:-
$detailArr=array(
array('name' => 'Ravi', 'coutry' => 'India'),
array('name' => 'Mac', 'coutry' => 'Canada'),
array('name' => 'Joy', 'coutry' => 'USA')
);
Suppose you have a multidimensional array and you only want a single key values column,then you should use loop function,this loop will run till the last key of the given array is traversed.
You just want to take out the column having name country. The array will be created dynamic so put [] brackets after it. In this brackets the key will be auto incremented.
you can see below code for better understanding
foreach ($detailArr as $CountryNmae) {
$CountryDetail[] = $CountryNmae['country'];
}
So final code will look like this
<?php
//define a array
$detailArr=array(
array('name' => 'Ravi', 'country' => 'India'),
array('name' => 'Mac', 'country' => 'Canada'),
array('name' => 'Joy', 'country' => 'USA')
);
//start loop
foreach ($detailArr as $CountryNmae) {
$CountryDetail[] = $CountryNmae['country'];
}
//print output
echo "<pre>";print_r($CountryDetail);die;
?>
Output will come following:
Array
(
[0] => India
[1] => Canada
[2] => USA
)
0 Comment(s)