user1355300
user1355300

Reputation: 4987

PHP undefined offset notice

I have the following if condition:

if ( 
    $items[ $count + 1 ]->menu_item_parent != $parent_id && 
    $submenu && 
    $items[ $count + 1 ]->menu_item_parent != $item->ID) {

    //something

}

I get the notice:

Undefined offset: 13

So I assume the 13 does not exist in the $items array and it can be avoided by checking with in_array. However I'm unsure how I can use that function in the above condition.

Upvotes: 0

Views: 1769

Answers (4)

Michel
Michel

Reputation: 4157

You could first check if $items[$count + 1] exists. Like

if( 
   //check first if $items[$count + 1] exists, else it breaks here
   isset($items[ $count + 1 ] )

   //now you know $item[$count + 1] exists, so you can continue
   &&
     ( 
        $items[$count + 1]->menu_item_parent != $parent_id && 
        $submenu && 
        $items[ $count + 1 ]->menu_item_parent != $item->ID
     ) 
   ){

    //something

  }

Upvotes: 3

Loko
Loko

Reputation: 6679

Ok so the in_array docs say:

in_array ( mixed $needle , array $haystack)

Where

needle = the searched value

haystack = the array

And you are not looking for the value, you're looking for the key

When you look at the bottom under see also, it says:

which is what you are looking for:

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index.

Perfect! Exactly what you want!

array_key_exists ( mixed $key , array $array )

where

key = value to check

array = array (duh!)

if ( array_key_exists($count + 1, $items))
    $items[ $count + 1 ]->menu_item_parent != $parent_id && 
    $submenu && 
    $items[ $count + 1 ]->menu_item_parent != $item->ID) {

    //something

}

Upvotes: 1

Answers_Seeker
Answers_Seeker

Reputation: 468

You should use a prefix test using isset method.

The call would look like that:

if (isset($items[ $count + 1 ])) { //do stuffs}

Upvotes: 1

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

if ( isset($items[ $count + 1 ]) && 
    $items[ $count + 1 ]->menu_item_parent != $parent_id && 
    $submenu && 
    $items[ $count + 1 ]->menu_item_parent != $item->ID) {

    //something

}

Upvotes: 7

Related Questions