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;
}

Recent posts View all

Web Dev

Updating payment method email addresses in Stripe

You can't update the email address associated with a payment method in Stripe via their dashboard, you need to use the Stripe CLI

Ruby

Irreversible Rails Migrations

What are irreversible migrations and how might we use them to our advantage?