...

View Full Version : ?: operator



paperino00
04-14-2012, 05:54 PM
Hello, does this code mean something like default $u is equal to the parameter get 'user', if it doesn't get 'user' try if the get parameter was userid, username, uid and u right?


$u = $_GET['user'];
$u = $u ? $u : $_GET['userid'];
$u = $u ? $u : $_GET['username'];
$u = $u ? $u : $_GET['uid'];
$u = $u ? $u : $_GET['u'];

Fou-Lu
04-14-2012, 06:14 PM
That's correct. ?: is the ternary operation, it is equivalent to:


$u = $_GET['user'];
$u = $u ? $u : $_GET['userid'];
$u = $u ? $u : $_GET['username'];
$u = $u ? $u : $_GET['uid'];
$u = $u ? $u : $_GET['u'];

// is the same as
$u = $_GET['user'];
if ($u == null)
{
$u = $_GET['userid'];
}
if ($u == null)
{
$u = $_GET['username'];
}
if ($u == null)
{
$u = $_GET['uid'];
}
if ($u == null)
{
$u = $_GET['u'];
}



But, this is not the correct approach to it. Since any and all of these may not exist, its best to check an isset boundary on them. The above will trigger notices on underfined offsets if you check the error logs or have error reporting enabled.
Since you have a priority, I'd simply pull the values of what is available and choose in that priority. Something simple like this:


$aPickFrom = array('user', 'userid', 'username', 'uid', 'u');
$aUsableKeys = array_keys($_GET);

$aAvailable = array_intersect($aUsableKeys, $aPickFrom);
if (isset($aAvailable[0]))
{
$u = $_GET[$aAvailable[0]];
}

print $u;

tangoforce
04-14-2012, 06:14 PM
The format is called a ternary.

Basically

$Something = ($If_something_is = true)? $DefaultValue: $ElseValue;


Beaten to it by Fou

Fou-Lu
04-14-2012, 06:19 PM
I win!
Although my comparison's are actually wrong. The more accurate would be:


if ($u != false)
{
$u = $u;
}
else
{
$u = 'the next one';
}

but I was too lazy to type all that.

tangoforce
04-14-2012, 06:22 PM
I win!

Bah.. next time Fou, next time :D :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum