Array check undefined offset php
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)){}
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.