I know the undefined offset gives out warning instead of error but I want to know is there any possible way to avoid this kind of warning to pop out? I intend to write a function to test the undefined offset because I think that writing multiple similar if-else
condition to test offset could be much work to be done.
function testOffset($item){
if(isset($item)){
return $item;
}else{
return "Nothing here!";
}
}
$array1[] = "Hello!";
echo testOffset($array1[1]);
In this case the function is work well but the warning will also pop out the moment I assign the unset element into function. Anyway to work around with it?
There are multiple ways of handling this problem, but depending on what you are trying to do you could do:
foreach($array as $key => $val) {}
If you are just trying to get 1 element based on the key, you should just go with array_key_exists:
$array1[] = "Hello!";
echo (array_key_exists(1, $array1)) ? $array[1] : "No key";