? and :

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
psychotomus
Forum Contributor
Posts: 487
Joined: Fri Jul 11, 2003 1:59 am

? and :

Post 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;
aCa
Forum Newbie
Posts: 11
Joined: Sun Apr 06, 2008 3:43 pm

Re: ? and :

Post 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

Code: Select all

 
($a ? $b : $c)
 
is the same as

Code: Select all

 
if ($a) {
  $b
} else {
  $c
}
 
psychotomus
Forum Contributor
Posts: 487
Joined: Fri Jul 11, 2003 1:59 am

Re: ? and :

Post by psychotomus »

theres two :?
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Re: ? and :

Post 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;
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: ? and :

Post 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.
Post Reply