View Full Version : Operator '?'
borris83
04-02-2009, 03:57 AM
Is there any operator that has '?' sign in php? If yes, then what is that for?
I am trying to understand some source code, and the statement is:
$app_root_path = (defined('APP_ROOT_PATH')) ? APP_ROOT_PATH : './';
Can you also explain the statement completely and what it does
JasonDFR
04-02-2009, 05:58 AM
It is called the ternary operator.
// something to evaluate ? 'value if true' : 'value if false';
$t = 'A';
//$t = 'B';
echo preg_match('/A/', $t) ? 'match' : 'no match';
Used inside the echo statement above, it says: Depending on whether or not preg_match() is true or false (1 or 0), echo match or no match. If preg_match() returns 1, the word 'match' is echoed. If preg_match() returns 0, the words 'no match' will be echoed.
Used inside your example, it says, if the constant APP_ROOT_PATH has been defined, set the $app_root_path variable equal to the value of the APP_ROOT_PATH constant. If APP_ROOT_PATH has not been defined, set the variable to './' Since the function defined() returns true or false, the ternary operator (?) can either use the first value after it if true, or the second, if false.
codeexploiter
04-02-2009, 06:23 AM
Terenary operator can be thought of as a simple if else construct:
The syntax:
[your_variable = ] expression ? true part : false part;
If your expression is evaluated to true then it will execute the true part or the false part.
More importantly, it returns the true or false part. Unlike the if statement, the ternary conditional operator forms an expression.
borris83
04-02-2009, 10:20 AM
Thank you all, Very informative... I searched for it in php.net... I don't know what keyword to use, and hence I searched for 'operators', but it wasn't listed there...
Cool! I never thought that I could write an 'IF ELSE' statement this way
It's on the comparison operators (http://www.php.net/operators.comparison) page, at the bottom of the article.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.