Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - get specific element form each sub array without looping

Tags:

php

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

like image 961
Marty Wallace Avatar asked Feb 17 '23 17:02

Marty Wallace


2 Answers

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:

  • array_map
  • array_reduce
  • array_walk
like image 125
Phill Sparks Avatar answered Mar 06 '23 16:03

Phill Sparks


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.

like image 41
Ashwini Agarwal Avatar answered Mar 06 '23 16:03

Ashwini Agarwal