Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Notice: Undefined index when looping array

Tags:

arrays

php

I'm looping a two-dimensional array like this:

if (!empty($aka)) {
    foreach ($aka as $ak) {
        if($ak["lang"]=="es") {
            $sptitle=$ak["title"];
        }
    }
}

Pretty simple. If the array ($aka) is not empty I loop trough it and when it finds that the "lang" index is equal to "es" I just save the "title" value for that index in $sptitle.

The problem is that the array ($aka) contains a lot of information and sometimes there is no "lang" index... and I get this error: Notice: Undefined index: lang.

How can I fix this???

This is a extract of the array to help you understand. Notice that [1] doesn't have a [lang] index but [2] does have:

[1] => Array
    (
        [title] => "The Lord of the Rings: The Motion Picture"
        [year] => ""
        [country] => "USA"
        [comment] => "promotional title"
    )

[2] => Array
    (
        [title] => "Señor de los anillos: La comunidad del anillo, El"
        [year] => ""
        [country] => "Argentina"
        [comment] => "Chile, Mexico, Peru, Spain"
        [lang] => "es"
    )

Thanks!

like image 416
Jonathan Avatar asked Mar 14 '09 11:03

Jonathan


1 Answers

Just test for it with isset, e.g.

if (!empty($aka)) {
        foreach ($aka as $ak) {
                if(isset($ak["lang"]) && ($ak["lang"]=="es")) {
                        $sptitle=$ak["title"];
                }
        }
}

If you're unaware of how a boolean operator like && can be short circuited, if the first operand is false, then the second operand won't be evaluated. You'll often see this idiom employed in checking for the availablilty of something before acting on it in the second operand.

You could also use array_key_exists('lang', $aka) instead of isset, it has slightly different semantics though - it will return true if an element is set to null, whereis isset would return false.

Interestingly, isset is at least twice as fast as array_key_exists, possibly due to the fact that it is a language construct rather than a regular function call.

like image 60
Paul Dixon Avatar answered Sep 18 '22 12:09

Paul Dixon