Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to assign a default value to a variable?

I have this right now to use a cookie value if exists otherwise use a default value:

$default_carat_min = "0.25";
if($_COOKIE["diamond-search_caratMin"])
{
    $default_carat_min = $_COOKIE["diamond-search_caratMin"];
}

I am going to have to do this with a lot of variables, and its going to get really cluttered/ugly. So I am trying to come up with a cleaner way of writing this.

I tried:

$default_carat_min = $_COOKIE["diamond-search_caratMin"] | "0.25";

Which did not work.

I can do this:

$default_carat_min = $_COOKIE["diamond-search_caratMin"] ? $_COOKIE["diamond-search_caratMin"] : "0.25";

But I don't like how I have to repeat the $_COOKIE twice. I am wondering if there is a way to write it something like my 2nd example?

like image 913
JD Isaacks Avatar asked Sep 21 '10 15:09

JD Isaacks


2 Answers

PHP 5.3 added a shortform for the ternary operator:

$default_carat_min = $_COOKIE["diamond-search_caratMin"] ?: "0.25";

Which evaluates to the left side if the left side is true, and evaluates to the right side otherwise.

Prior to 5.3, however, you'd have to use the long form.

like image 189
Daniel Vandersluis Avatar answered Nov 09 '22 16:11

Daniel Vandersluis


You can use a function :

function set_default(&$var, $default) {
    return isset($var) ? $var : $default;
}

$default_carat_min = set_default($_COOKIE["diamond-search_caratMin"], "0.25");
like image 36
Toto Avatar answered Nov 09 '22 15:11

Toto