I have some code like this :
somefunc($row['some_key']);
Sometimes, $row might not have 'some_key' which logs an Undefined index
warning.
How do you fix this warning without changing the current behavior of the program ?
I know I need to fix the problem to the source but this is a legacy codebase T_T
if(!isset($row['some_key'])){
somefunc(null);
}
else{
somefunc($row['some_key']);
}
Is this equivalent ?
Sure, it is equivalent, but you can be more terse (if you're interested) with a ternary operator (http://www.php.net/manual/en/language.operators.comparison.php you have to scroll a little, unfortunate, they don't have any anchor for it)...
somefunc( (isset($row['some_key'])) ? $row['some_key'] : null );
If you don't want to change the structure of the entire program, I would suggest adding a simple isset()
check before accessing any variable that throws an Undefined index/offset error.
if (isset($row['some_key'])) {
somefunc($row['some_key']);
}
This way, the function will get called if and only if the some_key
index exists. You could shorten it further using a ternary expression, but it would not be very readable, so I suggest using if-else
blocks instead.
You can also do like this:
somefunc( isset($row['some_key']) ? $row['some_key'] : null)