9

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]"
}
0

2 Answers 2

21

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

2 Comments

Or if you don't have PHP 5.5, you can use the userland implementation of array_column github.com/ramsey/array_column by the author of the official function
Since PHP 7.4 you can use arrow function to make it more compact: $plucked = array_map(static fn($item) => $item['email'], $yourArray);
2

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

2 Comments

Also nice approach, but I prefer @moonwave99's answer as it is a lean one liner.
@GottliebNotschnabel, No problem. I suggested this as a generalized solution as this will work even on multidimensional arrays.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.