PHP - Quick Is Not Set Replace
An issue that I encountered when I updated PHP and how I fixed it
During a recent PHP update I started getting a load of warnings in my code regarding undefined variables, whatever point release I was on must have been a little more relaxed about it than the newer version.
Some of the time it was obvious that it was bad coding on my part, some variables really did need to be assigned when I was assuming they were going to be assigned due to the flow of the code. Other times however I was left having to use isset() to see if a variable was set and if not act accordingly.
90% of the time acting accordingly meant set it to some value (usually NULL, 0 or ''). In order to keep my code nice and tidy I took 5 minutes to write a quick function to help, I leave it here on the chance it may be of some use to someone else as well.
/*
* This will either return itself or a passed in alternative
* depending on if the passed in variable is set or not.
*/
function issetOr(&$first, $alternative = NULL)
{
$output = '';
if (isset($first)) {
$output = $first;
} else {
$output = $alternative;
}
return $output;
}