views:

55

answers:

3

Essentially, I'd love to be able to define a variable as one thing unless that thing doesn't exist. I swear that somewhere I saw a shorthand conditional that looked something like this:

$var=$_GET["var"] || "default";

But I can't find any documentation to do this right, and honestly it might have been JS or ASP or something where I saw it.

I understand that all that should be happening in the above code is just to check if either statement returns true. But I thought I saw someone do something that essentially defined a default if the first failed. Is this something anyone knows about and can help me? Am I crazy? It just seems redundant to say:

$var=($_GET["var"]) ? $_GET["var"] : "default";

or especially redundant to say:

if ($_GET["var"]) { $var=$_GET["var"]; } else { $var="default"; }

Thoughts?

+3  A: 

In PHP 5.3+, you can do:

$var = $_GET["var"] ?: "default";

This is an extension to the ternary operator, borrowed from GCC et al.

Matthew Flaschen
Fantastic! That's what I was looking for. Googling it got me to something that seems to explain that Javascript does my above notation. Unfortunately, I don't have PHP 5.3 installed on my server, and that's not really up to me.
Ben Saufley
I forgot that I couldn't insert returns in my comment. Just wanted to end by saying thanks!
Ben Saufley
Matthew Flaschen
A: 

In such cases you should be checking for existence of the variable in $_GET and then whether it's valid for your parameters. For example:

$var = (isset($_GET["var"]) && $_GET['var'] !== '') ? $_GET["var"] : "default";

However, this can become pretty unreadably pretty quickly. I'd say keep it readable by first initializing your variable to a safe default, and then overwriting that with an external one, if that's valid:

$var = "default";
if (isset($_GET['var') && $_GET['var'] !== '') {
    $var = $_GET['var] ;
}

As for your first example, $var=$_GET["var"] || "default"; exists in Javascript: var someVar = incomingVar || "default";

Fanis
+1  A: 

Matthew has already mentioned the only way to do it in PHP 5.3. Note that you can also chain them:

$a = false ?: false ?: 'A'; // 'A'

This is not the same as:

$a = false || false || 'A'; // true

The reason why is that PHP is like most traditional languages in this aspect. The logical OR always returns true or false. However, in JavaScript, the final expression is used. (In a series of ORs, it will be the first non-false one.)

var a = false || 'A' || false; // 'A' 
var b = true && 'A' && 'B';    // 'B';
konforce