7

Is there a function in PHP to set default value of a variable if it is not set ? Some inbuilt function to replace something like:

$myFruit = isset($_REQUEST['myfruit']) ? $_REQUEST['myfruit'] : "apple" ;
gnur
  • 4,671
  • 2
  • 20
  • 33
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175

5 Answers5

9

PHP kind of has an operator for this (since 5.3 I think) which would compress your example to:

$myFruit = $_REQUEST['myfruit'] ?: "apple";

However, I say "kind of" because it only tests if the first operand evaluates to false, and won't suppress notices if it isn't set. So if (as in your example) it might not be set then your original code is best.

The function analogous to dictionary.get is trivial:

function dget($dict, $key, $default) {
    return isset($dict[$key]) ? $dict[$key] : $default;
}

For clarity, I'd still use your original code.

Edit: The userland implementation #2 of ifsetor() at http://wiki.php.net/rfc/ifsetor is a bit neater than the above function and works with non-arrays too, but has the same caveat that the default expression will always be evaluated even if it's not used:

function ifsetor(&$variable, $default = null) {
    if (isset($variable)) {
        $tmp = $variable;
    } else {
        $tmp = $default;
    }
    return $tmp;
}
Long Ears
  • 4,886
  • 1
  • 21
  • 16
1

As far as i know there exists nothing like this in PHP.

You may implement something like this yourself like

$myVar = "Using a variable as a default value!";

function myFunction($myArgument=null) {
    if($myArgument===null)
        $myArgument = $GLOBALS["myVar"];
    echo $myArgument;
}

// Outputs "Hello World!":
myFunction("Hello World!");
// Outputs "Using a variable as a default value!":
myFunction();
// Outputs the same again:
myFunction(null);
// Outputs "Changing the variable affects the function!":
$myVar = "Changing the variable affects the function!";
myFunction();
Thariama
  • 50,002
  • 13
  • 138
  • 166
  • Global variables are a code smell. You should avoid it. Anyway, this seems only to work with existing variables (`myFunction($x)` will still throw a notice), or static (hardcoded) values. – KingCrunch Feb 23 '11 at 10:14
1

You could also create a class implementing the ArrayAccess, which you pass 2 arrays during construction ($_REQUEST and an array with defaults) and make it choose the default value transparently.

Btw., relying on $_REQUEST is not a wise idea. See the manual on $_REQUEST for further information.

tobyS
  • 860
  • 1
  • 7
  • 15
0

Instead of testing, if a key not exists and then return a default value, you can also fill your array with this values, before accessing it.

$expectedKeys = array('myfruit');
$requestData = array_merge (
  array_combine(
    $expectedKeys,
    array_fill(0, count($expectedKeys), null)),
  $_REQUEST);

$postData is now an array with all keys you expect (specified by $expectedKeys), but any entry, that is missing in $_REQUEST is null.

$myFruit = $requestData['myfruit'];
if (is_null($myFruit)) {
  // Value not exists
}

But I also recommend to just stay with the ternary operator ?:.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
-1

There is a function called ife() in the CakePHP framework, you can find it here http://api13.cakephp.org/view_source/basics.php/, it is the last function!

You can use it like this:

echo ife($variable, $variable, 'default');
powtac
  • 40,542
  • 28
  • 115
  • 170
  • Using `@` to supress errors is never a really good idea, as long as you can avoid it. However: Whats the difference to `isset($variable) ? $variable : 'default'`? – KingCrunch Feb 23 '11 at 10:10
  • 1
    That's longer than the original code and uses error suppression (not good!) – Long Ears Feb 23 '11 at 10:11
  • @KingCrunch, I don't think there is a difference, often the `?:` "stlye" is not allowed in the coding guidelines. But I like it more since it is shorter and for my opinion well readable. – powtac Feb 23 '11 at 10:13
  • @Lacking Ideas, my fault, I changed the example usage. – powtac Feb 23 '11 at 10:15
  • If you format your code, the ternary operator is as readable as every other operator, Secondly, for others (--> non-CakePHP-developers/-users) the well-known operator is more intuitive, and finally its a bad argument to use a function, instead of an operator, just to save 4 (!) characters (if you omit every whitespace, its just 2 ;)). Additional: After your edit (removing the `@` operator) it will throw notices in exactly that cases, where it should help the developers. – KingCrunch Feb 23 '11 at 10:21