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
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With