Page 1 of 1
? and :
Posted: Tue Apr 08, 2008 3:12 pm
by psychotomus
i'm not sure what this means. can someone turn this into an if statement for me?
Code: Select all
return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
Re: ? and :
Posted: Tue Apr 08, 2008 3:19 pm
by aCa
It is a short version of if else.
The first expression before ? is the if statement. If that statement is true then you do whatever after the ? but if falsethen you do the thing after the :
This
is the same as
Re: ? and :
Posted: Tue Apr 08, 2008 3:42 pm
by psychotomus
theres two

Re: ? and :
Posted: Tue Apr 08, 2008 4:07 pm
by vigge89
The ?: is called the ternary operator and can be described like aCa wrote as a shorter version of if/else.
Code: Select all
return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
Can be translated into (quick edit):
Code: Select all
$return = $url;
if ($append_url) {
$return .= $url_delim . $append_url . $amp_delim;
} else {
$return .= $url_delim;
}
$return .= $params;
if (!$session_id) {
} else {
$return .= $amp_delim . 'sid=' . $session_id;
}
$return .= $anchor;
return $return;
Re: ? and :
Posted: Tue Apr 08, 2008 10:55 pm
by Chris Corbyn
Chaining ternaries is the work of the devil. Placing two in the same statement is almost as bad. If-then-else constructs are far easier to read. I generally only use ternaries for variable initialization.
Code: Select all
$foo = !empty($bar) ? $bar : null;
Generally this convention provides a more readable ternary too:
Code: Select all
$foo = !empty($bar)
? $bar
: null;
Looks funny with such a short expression, but with more realistic long variable names using multiple lines like that helps to make clear that there's a condition there.