Jump to content

Question: about ? and :


PureEvil

Recommended Posts

I've pretty much learned all of my PHP from a few books I'ver purchased and of course this kick ass web site.

The question is this. I keep seeing code like the following
[code]$row_color = ($Rcount % 2) ? $Talt_color1 : $Talt_color2;[/code]

What does the ? and the : mean in that string? I've been unable to find these in my books.

Thanks in advance.
Link to comment
https://forums.phpfreaks.com/topic/15152-question-about-and/
Share on other sites

Aha! From the manual:
[code]Left associativity means that the expression is evaluated from left to right, right associativity means the opposite. Example 15-1. Associativity

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?> 

Use parentheses to increase readability of the code.

[/code]

http://us2.php.net/manual/en/language.operators.php
Link to comment
https://forums.phpfreaks.com/topic/15152-question-about-and/#findComment-61051
Share on other sites

[quote author=ChaosXero link=topic=101251.msg400473#msg400473 date=1153408568]
It's an if/else statement I believe.

(if) ? true : false (but I might be wrong on the order.)
[/quote]

Ok I think I'm getting it maybe.

Basically in a nutshell your saying that if something is true or false do whats true or false.

Example:
[code]$i=1;
$Var1 = "i is 1";
$Var2 = "i is not 1";
$Var3 = ( $i == 1 ) ? $Var1 : $Var2;
echo("$Var3"); // should produce "i is 1"
[/code]

Is that correct?
Link to comment
https://forums.phpfreaks.com/topic/15152-question-about-and/#findComment-61142
Share on other sites

[quote author=ChaosXero link=topic=101251.msg400574#msg400574 date=1153414234]
I'm not sure really.  I'm at work, so I cant try, but if someone could try/confirm this, I'd be interested to know.
[/quote]

Seems to work... That is awesome and will come in extra handy. Honest to god I have four php books I pretty much live in while I'm trying to write my scripts, and not one of them said anything about this. Very handy...
Link to comment
https://forums.phpfreaks.com/topic/15152-question-about-and/#findComment-61146
Share on other sites

yes you are correct, it simplifies an if/else alot like the switch statement

$thefunc = ((isset($var)) && ($var != '')) ? _function ( $var, $var2 ) : $content = 'No Word Entered<br /><br />';

you can use it call and pass vars through a function and then $thefunc could have the value returned from your functions.. just an example
Link to comment
https://forums.phpfreaks.com/topic/15152-question-about-and/#findComment-61149
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.