0

I have am array containing these elements: id, email, type

I want to remove type and id and preserve email.

I have echoed and print_r the array and the subsequent elements and everything is fine.

But for filtering through the arrays and returning only the list emails, the following code is written, which, however does not work:

             $arr = array_walk($final_list, function($var){
                 return $var['email'];                 
           });

While if I echo $var['email'] it echoes the emails accordingly.

3
  • You shouldn't return from the array_walk callback, you pass by reference Commented Mar 9, 2014 at 14:04
  • 1
    array_walk is not the best function to use in this instance. I would suggest you take a look at array_column. Commented Mar 9, 2014 at 14:05
  • Note that array_column() requires PHP 5.5+, unless you use the userland implementation; but it is the best answer to what you're trying to do Commented Mar 9, 2014 at 14:06

2 Answers 2

1

You are using array_walk as if it were array_map. This would work:

$arr = array_map(function($var){ return $var['email']; }, $final_list);

On PHP 5.5+ there is also a more convenient way:

$arr = array_column($final_list, 'email');

Both of the above versions operate non-destructively: they create a copy of the email data from your input array.

For completeness only, and in the (unlikely) case that you do not want this because it uses up extra memory and instead prefer to modify your input by removing data from it, array_walk is an option:

array_walk($final_list, function(&$var){ // by reference!
    unset($var['id']);
    unset($var['type']);
});
Sign up to request clarification or add additional context in comments.

Comments

1

array_walk() is for applying a callback function to all the elements in the array. To filter the array, use array_filter() instead.

$arr = array_filter($final_list, function ($elem) {
    return $elem == 'email';
});

However, if you're using PHP 5.5+, you can use the very handy function array_column() to achieve this:

$arr = array_column($final_list, 'email');

If you're using an older version of PHP and cannot upgrade to PHP 5.5, you may use the Userland implementation of the function (written by the same author who wrote the array_column() function for PHP core). The source code is available on this GitHub repository.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.