($some_var) ? true_func() : false_func();
What is this in php, and what does this do? existence, boolean, or what?
($some_var) ? true_func() : false_func();
What is this in php, and what does this do? existence, boolean, or what?
It's the same thing as this:
if ($some_var) {
true_func();
}
else {
false_func();
}
If $some_val
is true, it executes the function before the :
.
If $some_val
is false, it executes the function after the :
.
It's called the ternary operator.
Typically it's used as an expression when assigning a value to a variable:
$some_var = ($some_bool) ? $true_value : $false_value;
It's one of the most abused programming constructs (in my opnion).
Taken from the PHP Manual: Comparison Operators
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
It's actually a ternary operator. (I mean the operator ?: is a ternary operator).
($some_var) ? func1() : func2();
'$some_var' is a boolean expression. If it evaluates to true 'func1()' is executed else 'func2()' is executed.
Well, the way it's written, it does the same as just
func();
(If $somevar
is true
, invoke func
; otherwise, invoke func
too!)
it checks for boolean:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements an object with zero member variables (PHP 4 only) the special type NULL (including unset variables) SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
Also have a look at: PHP type comparison tables