Page 1 of 1

What does it mean?

Posted: Fri Oct 22, 2010 7:23 am
by infomamun
Hi there
Below is a php syntax from admob (one advertising network) code:

Code: Select all

$rt = $ad_mode ? ($analytics_mode ? 2 : 0) : ($analytics_mode ? 1 : -1);
  if ($rt == -1) return '' ";
Would anybody explain me what are the meanings of "?" or ":" here?
Or in another word, what the syntax is telling actually?


It will be appreciated if someone gives me the links of online articles to know the uses of "?" or ":" in php syntax.

Regards

Re: What does it mean?

Posted: Fri Oct 22, 2010 7:39 am
by shiznatix
It is a simplified if{}else{} statment. Basically, this line:

Code: Select all

$rt = $ad_mode ? ($analytics_mode ? 2 : 0) : ($analytics_mode ? 1 : -1);
is exactly the same as this:

Code: Select all

if ($ad_mode)
{
    if ($analytics_mode)
    {
        $rt = 2;
    }
    else
    {
        $rt = 0;
    }
}
else
{
    if ($analytics_mode)
    {
        $rt = 1;
    }
    else
    {
        $rt = -1;
    }
}
so the first part is the condition ($something == $other) then comes if that first part evaluates to true ? so ($something == true ? 'it was true') then the : is the else part ($something == true ? 'it was true' : 'it was not true') and it returns either 'it was true' or 'it was not true' which can be then assigned to a variable like:
$was_it_true = ($something == true ? 'it was true' : 'it was not true');

Re: What does it mean?

Posted: Fri Oct 22, 2010 8:32 am
by twinedev
On a technical side, it is called ternary conditional operator and in the docs, just barely mentioned on: http://php.net/manual/en/language.expressions.php

-Greg

Re: What does it mean?

Posted: Fri Oct 22, 2010 8:34 am
by infomamun
Thanks a lot to both of you. Now I can understand it easily.

Re: What does it mean?

Posted: Fri Oct 22, 2010 8:59 am
by infomamun
one more question. I have posted a topic separately in this forum. Address of that topic is:
viewtopic.php?f=1&t=122516

What the query was in that topic, is-
A remote website/server has applied a redirection to a page, i.e it has applied a

Code: Select all

header(Location:'/newpath');
So while trying to grab the previous page, header returns 302 redirection with the following new location of the page:

Location: http://www.example.com/pageA.php?file=onefile?230562

so in that case, is the second "?" mark is a ternary operator? I meant is the header telling that

if(user click http://www.example.com/pageA.php?file=onefile){
then the new location is http://www.example.com/pageA.php?file=230562
}

haha...it's just my speculation. Is my thought is right or wrong? :lol:

Re: What does it mean?

Posted: Fri Oct 22, 2010 9:46 am
by s.dot
The ternary operator is strictly a programming thing.. Not a url thing.

On another note, nested ternary operators are terribly unreadable. One at a time is great though and may improve code readability.