Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten array in PHP?

I have an array that contains 4 arrays with one value each.

array(4) {
  [0]=>
  array(1) {
    ["email"]=>
    string(19) "[email protected]"
  }
  [1]=>
  array(1) {
    ["email"]=>
    string(19) "[email protected]"
  }
  [2]=>
  array(1) {
    ["email"]=>
    string(19) "[email protected]"
  }
  [3]=>
  array(1) {
    ["email"]=>
    string(19) "[email protected]"
  }
}

What is the best (=shortest, native PHP functions preferred) way to flatten the array so that it just contains the email addresses as values:

array(4) {
  [0]=>
  string(19) "[email protected]"
  [1]=>
  string(19) "[email protected]"
  [2]=>
  string(19) "[email protected]"
  [3]=>
  string(19) "[email protected]"
}
like image 572
Gottlieb Notschnabel Avatar asked Apr 08 '14 16:04

Gottlieb Notschnabel


People also ask

What does array [] mean in PHP?

Arrays ¶ An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.


2 Answers

In PHP 5.5 you have array_column:

$plucked = array_column($yourArray, 'email');

Otherwise, go with array_map:

$plucked = array_map(function($item){ return $item['email'];}, $yourArray);
like image 180
moonwave99 Avatar answered Oct 04 '22 16:10

moonwave99


You can use a RecursiveArrayIterator . This can flatten up even multi-nested arrays.

<?php
$arr1=array(0=> array("email"=>"[email protected]"),1=>array("email"=>"[email protected]"),2=> array("email"=>"[email protected]"),
    3=>array("email"=>"[email protected]"));
echo "<pre>";
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr1));
$new_arr = array();
foreach($iter as $v) {
    $new_arr[]=$v;
}
print_r($new_arr);

OUTPUT:

Array
(
    [0] => [email protected]
    [1] => [email protected]
    [2] => [email protected]
    [3] => [email protected]
)
like image 30
Shankar Narayana Damodaran Avatar answered Oct 04 '22 18:10

Shankar Narayana Damodaran