remove array from multidimensional array with unset

Viewed 103

Is it possible to remove an array from an array? This is how the array looks...

[1042] => Array
    (
        [contact_name] => XXX
        [email] => 
        [id] => XXX
    )

[1043] => Array
    (
        [contact_name] => XXX
        [email] => XXX
        [id] => XXX
    )

code...

foreach($contacts as &$contact){

    if(empty($contact['email']) || $contact['email'] == '')
        unset($contact);

}
4 Answers

It's possible if you use the arrays keys instead of references.

foreach($contacts as $key => $contact){
    if(empty($contact['email']))
        unset($contacts[$key]);
}

I also removed the $contact['email] == '' since the empty()-check covers empty (!) strings as well.

Note: In general, avoid using references together with foreach if you can. Using them can easily lead to unwanted side effects.

Make use of the key and value pair when defining the foreach loop.

Knowing the key of the value (in this case a subarray) you want to unset, you can do it like below:

foreach($contacts as $key => $contact {
     if(empty($contact['email']) || $contact['email'] == '') {
        unset($contacts[$key]);
    }
}

It looks like you want to filter out items that do not have a value in the email field, if that is the case then use PHP's array_filter method:

$filtered = array_filter($array, function($contact) {
    if(!empty($contact['email']) && $contact['email'] != '') {
        return $contact;
    }
});

Fiddle: Live Demo

had to do traditional for loop and use index to remove. Could not be done with foreach loop.

Edit

 // this is the code that worded
for($i = 0; $i <= count($other_array); $i++){
    if( !array_key_exists( "testing", $other_array[$i] ) )
        unset($other_array[$i]);
}
Related