2
Array
(
    [user_mob_1] => Array
        (
            [mob_code] => 06
            [mob] => 069633345
            [type] => 1
            [phone_id] => 0
        )

    [user_mob_2] => Array
        (
            [mob_code] => 07
            [mob] => 07123456
            [type] => 1
            [phone_id] => 
        )

    [user_mob_6] => Array
        (
            [mob_code] => 0
            [mob] => 
            [type] => 1
            [phone_id] => 0
        )

)

The goal is to remove user_mob_* where mob is empty !

The answer is:

foreach($array as $key => $row) {
   if(empty($row['mob'])) unset($array[$key]);
}

Simple, but I'm new in php and first I thinked to use functions like array_filter etc.

All ingenious is simple.

4
  • please use the search function before asking questions. This has been asked and answered multiple times before. Do your homework Commented Mar 13, 2012 at 9:29
  • 2
    The correct way to answer your own question is as an answer (rather than in the question). That way people can vote for all answers given and the best one can rise to the top. Commented Mar 13, 2012 at 9:42
  • If you use unset the array will need a sort anyway because those keys won't be ordered anymore. Commented Nov 14, 2012 at 12:21
  • @alexei try this one Commented Oct 16, 2014 at 13:22

1 Answer 1

26

Your idea of using a built-in function like array_filter is a very good one; PHP has lots of these that can make your life easier.

Specifically, array_filter accepts a callback that you can use to customize the filtering logic. This would work:

$filtered = array_filter($array, function($el) { return !empty($el['mob']); });

Here the callback is supplied as an anonymous function.

Sign up to request clarification or add additional context in comments.

4 Comments

I didn't downvote, but if you notice the question, there was no question asked and your solution doesn't do what the questioner said the solution was.
@Paul: Sorry for digging this up so long afterwards (I came here due to Matt's comment), but the answer is almost equivalent to what the OP gives (the difference being that the OP's modifies the input array directly while this creates a filtered copy).
Also the OT's answer builds on the fact that foreach works on a copy of the input array. Doing the same with any other loop would lead to very undesireable results. What I'm trying to say is that for php beginners, seeing the orignal answer could lead them to believe it's a safe thing to do without knowing why it actually works.
Anonymous functions are only available from php ver 5.3.0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.