Array check undefined offset php - 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 :)

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.

Related

Why is a varibale "NULL" instead of being undefined?

I was expecting to see a notice like PHP Notice: Undefined variable: a, however when I run this code it works perfectly fine. Moreover, the variable becomes NULL. Why?
<?php
function($a = 1) use (&$a) {};
var_dump($a); // NULL <---- Expected a Notice "undefined", got "NULL"
Demo
i think the & operator silently create the variable if it doesn't exist already. seems this page try to explain it:
If you assign, pass, or return an undefined variable by reference, it will get created. , so when you do use (&$a) , & sees that $a doesn't already exist, and create it..
as for undefined, that's not a real type in PHP. (unlike, for example, javascript, which actually have a type called undefined, and a separate type called null)
why null? given that undefined doesn't exist, its the only logical choice for the initial value, what did you expect it to be initialized to?
"If you don't initialize your variables with a default value, the PHP will do a type cast depending on how you are using the variable. This sometimes will lead to unexpected behaviour."

Finding Out if a Value in a Generated Array Exists Without Getting a Notice

I have an array, $beerArray, that is obtained from parsing data from a JSON API and putting it into a PHP array. There are certain values, like $beer_name, that I expect to be in the JSON data but aren't always there, causing that value to not exist in the array. I've set up some if... else statements to adjust for these cases:
if (!($beerArray->response->beer->beer_name)) {
do something
}
else {
do something else
}
}
This prevents errors like trying to assign a variable to an array value that doesn't exist, but I still get this pesky Notice:
Notice: Undefined property: stdClass::$beer_name in /Users/x_/Documents/html/php/populatebeer.php on line 66
Is there a better way to structure my logic to avoid these notices? It fills the log with false positives which I'd like to avoid.
Use the isset() function. Simply pass the variable you wish to see is set or not and this function will return true if the variable exists or false if it does not.
For example change your if statement to:
if (!isset($beerArray->response->beer->beer_name)) {
The first block executes if there is no beer_name set. The 2nd block executes if it has a name
Here is the documentation: http://php.net/manual/en/function.isset.php

Calling isset() vs. returning undefined index

I have code that is used very extensively which fetches an array from another method, and sometimes returns the first element of that array. Given that null is an acceptable return value for the function, is it worth the performance overhead of calling isset() on the array index (or checking the array length, etc), or is it better to just return the non-existant index (warnings aside). What are the advantages of calling isset() aside from preventing the warning.
The example below is simplified, the real function doesn't just get the first element of the array.
Return index which may not exist:
function get_array_element(){
$array = get_array(); // function that returns array
return $array[0]; // return index 0 which may not exist
}
Versus checking if index is set:
function get_array_element(){
$array = get_array(); // function that returns array
return (isset($array[0]))? // check if index 0 isset() else return null
$array[0] :
null;
}
Throwing a notice when accessing an undefined index -- in theory -- should alert you for typos in key names. In practice, if you’re using isset first, you probably just copied the key name there. Or used a numeric index. Or a constant.
On the other hand, in most cases you’re accessing an index withour caring wether it’s set or not -- and in this scenario, using isset is just anoying. A lot of languages lets you just retrieve any index without warnings, Javascript for example: just returning an undefined.
So I would advice to ignore the notice. Not all of them, because in some cases there really are helpful, so keep them turned on in development, but silence such array access by using #. Yes, it is ugly, but does its job:
return #$array[0];
Or in simple cases, maybe other solutions fit?
return array_shift($array);
Calling isset inside that function is semi-pointless because you are returning null if it doesn't exist, but null will be returned from $array[0] regardless of whether you use isset of not.
If it only throws an E_NOTICE then I wouldn't worry about it, just check for get_array_element() == null.

how to check for Notice (8) Undefined index

I know why I am getting this error, and this is because there currenly no ratings for this specific dish, so it is null or empty but I am not sure how to handle it.. I tried this but still the same error came up..
if(empty($rate_dishes[$j]["DishRating"]["dish_id"]))
{
echo $this->Form->hidden('dish_id', array('value'=> $this->params['var']));
}
else
{
echo $this->Form->hidden('dish_id', array('value'=> $rate_dishes[$j]["DishRating"]["dish_id"]));
}
Basically I am providing the dish id if its not provided by the posted array.. Whenever there is a rating for that particular dish it takes the 'else' condition.. but if it does not have a rating.. it gets to the first condition and still shows that error..
the URL would be /special_dishes/rate_dishes/4/?var=4
You probably shouldn't check for empty indices in that case, but rather if the array key exists. This is not really a feature of CakePHP, but rather just a standard PHP method.
The PHP function for this is isset() rather than empty(), as the latter expects the key to be there:
isset($rate_dishes[$j]["DishRating"]["dish_id"])
Also, there's array_key_exists(), but I believe you're looping through all the data in that post array, so using isset() is probably just fine.

PHP is it OK to try access an associative array if you are unsure the key exists?

Is it OK to rely on PHP's behaviour if a key is not in the array? Which is:
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.
For instance if I do not know $_POST contains certain keys is it OK to just try? I want the result to be null anyway. Or is there a better way?
Since you should always develop with error reporting turned on, you want to avoid triggering avoidable errors so as to keep error reporting useful to you. As such, no, it's not okay. Use isset or empty. For a more in-depth excursion into this topic see The Definitive Guide To PHP's isset And empty.
You can use isset() to check if it exists and if so do stuff.
if(isset($_POST["key"])){// do stuff}
You should use isset() or empty() to test it.
If it is necessary to check if a key exists even if it the key is set to null then array_key_exists(mixed $key , array $search) will be usefull. But it is very slow compared to isset(). So isset() shall be used if you check for a key that is in the array and not null.
isset()function can save you from the warning of index not found by checking for it first
isset($_POST['notSure']) ? $var= $_POST['notSure'] : $var = null;

Categories