12

Is there any way to get all values in one array without using foreach loops, in this example?

<?php 
$foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]);

The output I need is array("a", "b", "c")

I could accomplish it using something like this

$stack = [];

foreach($foo as $value){
  $stack[] = $value["type"];
}

var_dump($stack); 

But, I am looking for options that does not involve using foreach loops.

iOi
  • 403
  • 3
  • 8
  • 26

2 Answers2

21

If you're using PHP 5.5+, you can use array_column(), like so:

$result = array_column($foo, 'type');

If you want an array with numeric indices, use:

$result = array_values(array_column($foo, 'type'));

If you're using a previous PHP version and can't upgrade at the moment, you can use the Userland implementation of array_column() function written by the same author.

Alternatively, you could also use array_map(). This is basically the same as a loop except that the looping is not explicitly shown.

$result = array_map(function($arr) {
   return $arr['type'];
}, $foo);
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • 1
    Sadly I am not using 5.5 Which I should be. – iOi Mar 31 '14 at 11:40
  • 1
    `array_values()` isn't required here as `array_column()` will return desired array – Alma Do Mar 31 '14 at 11:41
  • @AlmaDo: I'm aware. I just thought maybe the OP wanted to get an array with numeric indices. – Amal Murali Mar 31 '14 at 11:41
  • 1. link is broken. 2. It's much better to update PHP than using external lib just because of one function – Alma Do Mar 31 '14 at 11:44
  • array_map is a bit similar to looping imho. I was looking something along by combining `each()` or `array_values()` I guess its not possible. Thanks anyway – iOi Mar 31 '14 at 11:49
  • @AlmaDo: 1. I was typing it from memory and made a typo :D It's been fixed, thanks! 2. I wouldn't call it a library. It's just a simple function. Take a look at the [code](https://github.com/ramsey/array_column/blob/master/src/array_column.php#L31) if you want. I agree with you that an upgrade is always preferable. But for some folks, a quick upgrade is not *always* possible. ;) – Amal Murali Mar 31 '14 at 12:06
  • @iOi It's okay! No hard feelings there. I'm glad you solved the problem at hand, nonetheless ;) – Amal Murali Mar 31 '14 at 12:36
  • @AmalMurali Feel free to jump on board [on the next question if you want](http://stackoverflow.com/questions/22761727/getting-mysql-column-from-the-command-line) – iOi Mar 31 '14 at 12:38
5

Either use array_column() for PHP 5.5:

$foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]);
$result = array_column($foo, 'type');

Or use array_map() for previous versions:

$result = array_map(function($x)
{
   return $x['type'];
}, $foo);

Note: The loop will still be performed, but it will be hidden inside the aforementioned functions.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Alma Do
  • 37,009
  • 9
  • 76
  • 105