Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to set default value of associative array if the key is not present

Tags:

php

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" ;
like image 402
DhruvPathak Avatar asked Feb 23 '11 09:02

DhruvPathak


People also ask

How do you find the key of an associative array?

Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

Which function is used to sort an associative array?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

How do you change the key in an associative array?

Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair. Save this answer.


2 Answers

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;
}
like image 54
Long Ears Avatar answered Sep 19 '22 18:09

Long Ears


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();
like image 38
Thariama Avatar answered Sep 19 '22 18:09

Thariama