Skip to content

Instantly share code, notes, and snippets.

@runekaagaard
Created April 21, 2011 14:21
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 runekaagaard/934612 to your computer and use it in GitHub Desktop.
Save runekaagaard/934612 to your computer and use it in GitHub Desktop.
firstset, firstfull, setor, fullor userland implementation.
<?php
// Errors on.
error_reporting(E_ALL);
ini_set('display_errors', 1);
/**
* Returns the first passed argument that is set.
*
* @return mixed
*/
function firstset(&$v0=null, &$v1=null, &$v2=null, &$v3=null, &$v4=null,
&$v5=null, &$v6=null, &$v7=null) {
foreach (func_get_args() as $arg) {
if(isset($arg)) {
return $arg;
}
}
return null;
}
/**
* Returns the first passed argument that is not empty.
*
* @return mixed
*/
function firstfull(&$v0=null, &$v1=null, &$v2=null, &$v3=null, &$v4=null,
&$v5=null, &$v6=null, &$v7=null) {
foreach (func_get_args() as $arg) {
if(!empty($arg)) {
return $arg;
}
}
return none;
}
/**
* Sets the passed value by reference to itself if it is set, otherwise to the
* default value.
*
* @param mixed $value
* @param mixed $default
*/
function setor(&$value, $default) {
$value = isset($value) ? $value : $default;
return $value;
}
/**
* Sets the passed value by reference to itself if it is not empty, otherwise
* to the default value.
*
* @param mixed $value
* @param mixed $default
*/
function fullor(&$value, $default) {
$value = !empty($value) ? $value : $default;
return $value;
}
/**
* Short for "as reference". Makes passed argument referenceable.
*
* @param mixed $v
* @return mixed
*/
function &ar($v) {
return $v;
}
/**
* Example code below, solves the goal from https://gist.github.com/909711.
*/
// Dummy function and class.
function foo() { return null; }
class Bar {
function get() { return null; }
static function get2() { return null; }
}
$bar = new Bar();
// Set one variable from another or a default value.
// 1a.
$a = firstset($o, ar('Default value 1'));
// 1b.
$b = firstfull($p, ar('Default value 2'));
// Set one variable from itself or a default value.
// 2a.
setor($c, 'Default value 3');
// 2b.
fullor($d, firstfull($z, ar('Default value 4')));
// Find the first set value from a range of variables and statements.
// 3a.
$e = firstset($s, ar(null), ar(foo()), ar($bar->get()), ar(Bar::get2()),
$t['key']['key2']['key3'], $u->key1->key2->key3, ar('Default value 5'));
// 3b.
$f = firstfull($v, ar(0), ar(foo()), ar($bar->get()), ar(Bar::get2()),
$x['key']['key2']['key3'], $y->key1->key2->key3, ar('Default value 6'));
var_dump(compact(range('a', 'f')));
/*
Outputs:
array(6) {
["a"]=>
string(15) "Default value 1"
["b"]=>
string(15) "Default value 2"
["c"]=>
string(15) "Default value 3"
["d"]=>
string(15) "Default value 4"
["e"]=>
string(15) "Default value 5"
["f"]=>
string(15) "Default value 6"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment