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.

2
  • Do you want to use for loops? Commented Mar 31, 2014 at 11:36
  • @magnetronnie even worse :) Commented Mar 31, 2014 at 11:39

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

8 Comments

Sadly I am not using 5.5 Which I should be.
array_values() isn't required here as array_column() will return desired array
@AlmaDo: I'm aware. I just thought maybe the OP wanted to get an array with numeric indices.
1. link is broken. 2. It's much better to update PHP than using external lib just because of one function
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
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.