Making a personal calendar that displays text - long description (obtained from a db) if text exists. This works but I get a server log error saying that there is an undefined offset: for ($i=1; $i<=$no_of_days; $i++){ if($lng_desc[$i]){ echo $lng_desc[$i]; } } It's not complaining about the offset when there is a description, only on days when there is no description. I thought that the if would negate this - if true display text, if not (do nothing as there is no else). What is wrong here?
In your if statement, you are assuming the index exists and simply checks whether the value stored in that index computes to the boolean value 'true'. e.g.: non-empty string, non-zero int, etc.
I tried if array_key_exists (thank you by the way) and received the following error: Undefined variable: lng_desc array_key_exists() The second argument should be either an array or an object More help?
<?php for ( $i = 1; $i <= $no_of_days; ++$i ) { if ( isset($lng_desc[$i]) ) { echo $lng_desc[$i]; } } PHP:
You most probably misspelled something? If you simply replaced your old if statement with the one I suggested, the notice shouldn't occur if it didn't occur with the old code. You could add another check in your if statement to check if $lng_desc has been defined to clear the notice, but most probably that would just give you a logic error (nothing being printed). Check why $lng_desc would suddenly be undefined there.
Thanks guys. The isset fixed it. I knew about isset (and use it), but it just didn't dawn on me to use it here.
Beware that isset() has the weird behaviour that it will still return 'false' if the variable is actually set but has the value 'NULL'. Probably not an issue in your case but I'd always use array_key_exists() to be on the safe side, unless when I really want to check that the value is not null as well.
PHPer, Thank you for the feedback. I'll try to remember the side effect of isset(). Now that I have all the other errors fixed (there were a couple I kept to myself), I'll try your suggestion again.