Dolis
Dolis

Reputation: 335

Array check undefined offset php

I'll try to explain it.

i have a array:

 $arrayTime = array(0=>"07",1=>"09", 3=>"13", 4=>"15", 5=>"17", 6=>"19");

Here you can see that is not defined offset 2 and now i need for my array and on offset 2 push number 0(for example) I tried use this:

if($arrayTime[$i]==""){
   $arrayTime[$i]=0;
}

Yes it works but 50 to 50 array looks like this:

$arrayTime = array(0=>"07",1=>"09", 3=>"13", 4=>"15", 5=>"17", 6=>"19",2=>"0");

but on the line where is the if it throws an error:

Notice: Undefined offset: 2 in C:\wamp\www\xxx.php on line 10

So i need same result, but without error. Thanks for your help all :)

Upvotes: 17

Views: 62825

Answers (2)

Xorifelse
Xorifelse

Reputation: 7911

First of all, it doesn't throw an error. It gives you a warning about a possible bug in your code.

if($arrayTime[$i]==""){}

This attempts to access $arrayTime[$i] to retrieve a value to compare against your empty string.

The attempt to read and use a non-existing array index to get a value for comparison is the reason why it throws the warning as this is usually unexpected. When the key does not exist null is used instead and the code continues executing.

if(null == ""){} // this evaluates to true.

Because you are comparing against an empty string "", your answer would be empty():

if(empty($arrayTime[$i])){}

It means you are expecting a key not to exist and at the same time you are checking the value for emptyness. See the type comparison table to see what is and what is not considered 'empty'.

The same rules apply to isset() and is_null(), it wont throw the notice if the key does not exist. So choose the function that best serves your needs.

Keep in mind that by using any of these functions you are checking the value and not if the key exists in the array. You can use array_key_exists() for that.

if(array_key_exists($i, $arrayTime)){}

Upvotes: 31

Pabhoz
Pabhoz

Reputation: 86

to add zeroes to your non-defined indexes without getting a Notice you should evaluate if the desired index to compare exists, so instead of comparing directly try checking the existence of the index first by using isset method, checking if the variable is defined and isn't NULL.

So your code to validate should look like this:

    //check for the index before tryin' to acces it
    if( !isset($arrayTime[$i]) ){
       $arrayTime[$i]=0;
    }

Hope it works for you.

Upvotes: 5

Related Questions