tags:

views:

2356

answers:

2

Hi, 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!

+7  A: 

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.

Paul Dixon
I personally prefer array_key_exists, but use isset specifically because it's (surprisingly) a LOT faster http://us.php.net/manual/en/function.array-key-exists.php#82867
enobrev
Interesting result, will add to answer
Paul Dixon
Um, isset($ak['lang']) will still raise an E_NOTICE of undefined index. array_key_exists() will not.
cletus
isset will not raise a notice, try it.
Paul Dixon
A: 

would it be wrong to use:

if (@$ak['lang']) 

i really miss the fact that we can't still do the 2 checks in 1 like so

if ($ak['lang']) 

it was one of the beautiful things about PHP and I just don't see the purpose of warning whether an array key is initialised in a transient scripting language like PHP.

i'm not sure where the developers of PHP are going with this. personally, i'm a bit worried that they're morphing PHP into something else. just leave it alone. it was great.

Justin Lawrence