Reputation: 35754
In php is there a way to get an element from each sub array without having to loop - thinking in terms of efficiency.
Say the following array:
$array = array(
array(
'element1' => a,
'element2' => b
),
array(
'element1' => c,
'element2' => d
)
);
I would like all of the 'element1' values from $array
Upvotes: 4
Views: 1691
Reputation: 3823
Without loop? Recursion!
$array = array(
array(
'element1' => 'a',
'element2' => 'b'
),
array(
'element1' => 'c',
'element2' => 'd'
)
);
function getKey($array,$key,$new = array()){
$count = count($array);
$new[] = $array[0][$key];
array_shift($array);
if($count==1)
return $new;
return getKey($array,$key,$new);
}
print_R(getKey($array,'element1'));
As I understood from Wikipedia Recursion is not a loop.
Upvotes: 0
Reputation: 212452
If you're running PHP 5.5 (currently the beta-4 is available), then the following
$element1List = array_column($array, 'element1');
should give $element1List as an simple array of just the element1 values for each element in $array
$array = array(
array(
'element1' => a,
'element2' => b
),
array(
'element1' => c,
'element2' => d
)
);
$element1List = array_column($array, 'element1');
print_r($element1List);
gives
Array
(
[0] => a
[1] => c
)
Upvotes: 2
Reputation: 4858
You can use array_map.
Try code below...
$arr = $array = array(
array(
'element1' => a,
'element2' => b
),
array(
'element1' => c,
'element2' => d
)
);
print_r(array_map("getFunc", $arr));
function getFunc($a)
{
return $a['element1'];
}
See Codepad.
But I think array_map will also use loop internally.
Upvotes: 2
Reputation: 20909
There are a number of different functions that can operate on arrays for you, depending on the output desired...
$array = array(
array(
'element1' => 'a',
'element2' => 'b'
),
array(
'element1' => 'c',
'element2' => 'd'
)
);
// array of element1s : array('a', 'c')
$element1a = array_map(function($item) { return $item['element1']; }, $array);
// string of element1s : 'ac'
$element1s = array_reduce($array, function($value, $item) { return $value . $item['element1']; }, '');
// echo element1s : echo 'ac'
array_walk($array, function($item) {
echo $item['element1'];
});
// alter array : $array becomes array('a', 'c')
array_walk($array, function(&$item) {
$item = $item['element1'];
});
Useful documentation links:
Upvotes: 4