Home » Php » Unset variable from php array

Unset variable from php array

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an array which when printed out, looks something like below, although there are dozens of warning and success messages available:

Array
(
    [warning] => Array
        (
            [0] => We might have a problem.
            [1] => You might have a problem.
            [2] => They may have a problem.
        )

    [success] => Array
        (
            [0] => Everything is awesome
        )

)

I need to look in the array and find the warning with string value You might have a problem.. So I have the following code:

foreach($msgArray as $msgType => $messages) {
    foreach($messages as $message => $msg) {
        if($message == 'warning' && $msg == 'You might have a problem.'){
            unset($msgArray[$msgType]);
        }
    }
}

But unfortunately this removes all $msgType of warning from the $msgArray.

How can I remove just the warning with value “You might have a problem.”?

Thanks!

How to&Answers:

You’re removing the top level key. Just remove the second-level one instead:

unset($msgArray[$msgType][$message]);

P.S. Given the data and code you’ve shown, $message will never be warning. $msgType will be.

Answer:

One line will do it without the loops and comparisons. Just search for the message to return the key and unset it:

unset($msgArray['warning'][array_search('You might have a problem.', $msgArray['warning'])]);