2

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

}
1
  • 3
    Call unset at the desired index: unset($array[1043]); Commented Sep 13, 2018 at 17:54

4 Answers 4

2

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.

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

1 Comment

once I try I will comment on result - Thank you for the quick response
0

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

Comments

0

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

Comments

0

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

1 Comment

You could consider adding the code to your answer to illustrate your solution.

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.