"09", 3=>"13", 4=>"15", 5=>"17",...">

Array check undefined php offset

I will try to explain this.

i has an array :

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

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

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

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

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

but in the line where the if , it throws an error:

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

I need the same result, but no errors. Thank you for your help:)

+5
source share
2 answers

First of all, this does not cause an error. This gives you a warning about a possible error in your code.

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

This is an attempt to access $arrayTime[$i] to get a value to compare with an empty string.

Trying to read and use a nonexistent array index to get a value for comparison is the reason it throws a warning, as this is usually unexpected. When the key does not exist, null used instead, and the code continues to execute.

 if(null == ""){} // never true. 

Since you are comparing with the empty string "" , your answer will be empty() :

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

This means that you expect that the key will not exist, and at the same time you check the value for empty. 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 does not throw a notification if the key does not exist. Therefore, select the function that best suits your needs.

Keep in mind that using any of these functions you check the value , but not if the key exists in the array. You can use array_key_exists() for this.

 if(array_key_exists($i, $arrayTime)){} 
+8
source

in order to add zeros to your undefined indexes without receiving a Notification, you must evaluate whether the required index exists for comparison, so instead of directly comparing, try checking for the index first using isset , checking to see if the variable is defined and is not NULL.

So, your verification code should look like this:

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

Hope this works for you.

0
source

Source: https://habr.com/ru/post/1265935/


All Articles