Tidbit: Cascade through variables in PHP

August 19th 2021 · 90 words, about 1 minute read

While working on Diary.by I realized that I needed a tiny bit of functionality - iterate through a series of variables and output the first, non-empty, not-null variable.

I also realized that I couldn't find something like this anywhere in the docs. Thinking it really does not exist (it really doesn't?), I came up with the following method. Feel free to use it if you need to.

public static function cc(...$vars) {
    foreach ($vars as $var) {
        if (isset($var) && !is_null($var) && !empty($var)) return $var;
    }
    return '';
}