Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting array values without foreach loop

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.

like image 841
iOi Avatar asked Mar 31 '14 11:03

iOi


People also ask

How to get value from array without loop?

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);

Which is faster forEach or while?

There is no major "performance" difference, because the differences are located inside the logic. You use foreach for array iteration, without integers as keys. You use for for array iteration with integers as keys. etc.

What is forEach loop in array?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.

What is forEach loop with example?

In this program, foreach loop is used to traverse through a collection. Traversing a collection is similar to traversing through an array. The first element of collection is selected on the first iteration, second element on second iteration and so on till the last element.


1 Answers

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);
like image 169
Amal Murali Avatar answered Sep 28 '22 19:09

Amal Murali