Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Last active September 10, 2018 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcaskill/dfcbb53d570f579c4405cc2ab09ef1de to your computer and use it in GitHub Desktop.
Save mcaskill/dfcbb53d570f579c4405cc2ab09ef1de to your computer and use it in GitHub Desktop.
PHP : Sets a given variable if it is not set with the last parameter or the first non-empty value.

fallback

(PHP 5 >= 5.6)
fallback — Sets a given variable if it is not set.

Description

mixed fallback( mixed &$var [, mixed $... ] )

This function sets $var if it is not set with the last parameter or the first non-empty value.

Based on Alex Suraci's fallback() function. Updated for PHP 5.6.

Parameters

  • var — The variable to return or set.
  • ... — Another variable…

Return Values

Returns the value of whatever was chosen.

Examples

Example #1 fallback() example

function datetime($when = null) {
	fallback($when, time());
	$time = (is_numeric($when)) ? $when : strtotime($when) ;
	return date("Y-m-d", $time);
}

$nextWeek = time() + (7 * 24 * 60 * 60);

echo 'Now:       '. datetime() ."\n";
echo 'Next Week: '. datetime($nextWeek) ."\n";

The above example will output:

Now:       2005-03-30
Next Week: 2005-04-06

Installation

With Composer

$ composer require mcaskill/php-fallback

Without Composer

Why are you not using composer? Download Function.Fallback.php from the gist and save the file into your project path somewhere.

{
"name": "mcaskill/php-fallback",
"description": "Sets a given variable if it is not set.",
"license": "MIT",
"authors": [
{
"name": "Chauncey McAskill",
"email": "chauncey@mcaskill.ca",
"homepage": "https://github.com/mcaskill"
}
],
"keywords": [
"function"
],
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"require": {
"php": ">=5.6.0"
},
"autoload": {
"files": [ "Function.Fallback.php" ]
}
}
<?php
if (!function_exists('fallback')) {
/**
* Sets a given variable if it is not set.
*
* The last of the arguments or the first non-empty value will be used.
*
* @link https://github.com/vito/chyrp/ Origin of function.
* @param mixed $var The variable to return or set.
* @param mixed ...$args Variable list of arguments to serve as fallbacks.
* @return mixed The value of whatever was chosen.
*/
function fallback(&$var, ...$args)
{
if (is_bool($var)) {
return $var;
}
$set = (!isset($var) || (is_string($var) && trim($var) === '') || $var === []);
if (count($args) > 1) {
foreach ($args as $arg) {
$fallback = $arg;
if (isset($arg) && (
!is_string($arg) || (
is_string($arg) &&
(trim($arg) !== '')
)
) &&
($arg !== [])
) {
break;
}
}
} else {
$fallback = (isset($args[0]) ? $args[0] : null);
}
if ($set) {
$var = $fallback;
}
return ($set ? $fallback : $var);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment