PHP "Ternary Like" Boolean Expression Curiosity [duplicate] - php

This question already has answers here:
Short-circuit evaluation via the AND operator in PHP
(5 answers)
Closed 6 years ago.
This is just more of a "why does it work" and "why or why not use it" type question.
We all know PHP expressions using ternary operations
$var = (isset($i) ? true:false);
But in PHP something like the following works too. (It is not ternary, 3 parts, it is more of a binary operation, 2parts.)
$var = true;
isset($i) || $var = false;
Which may not be so practical :) but a more useful construction is
isset($i) || exit();
So the above (much better looking imo) would have the same result as
if(!isset($i)) exit();
But other than the common
defined('CONSTANT') || define('CONSTANT','FOO');
I rarely see this type of construct used in PHP. Why does this work? What is it called. Why is it not taught or used more. Are there cons to using it? And is there practical ways to use && in the same way?

This way of writing statements also exists in C, Perl and other languages, it plays with how the compiler evaluates statements chained with logical operators.
Imagine you have an expression if (a() or b()), then when a() returns true you don't have to evaluate b(), because the entire statement is true already. So b() is only called when a() is false. You can write this without the if, it still works the same way.
This shorthand is usually found like you described, to define default values or exit if a condition is not met.

Related

The difference when using if statement true === something() vs something() === true [duplicate]

This question already has answers here:
Variable position in comparision in PHP
(4 answers)
Closed 2 years ago.
I've seen a lot of codes that places boolean in front, followed by comparison operator, and then the variable/function to test
if (true === something()) {
doStuff();
}
Instead of the usual
if (something() === true) {
doStuff();
}
Is there a real difference between them instead of personal preference?
The practice to put the value first for comparisons originates from a time when == was commonly used as a comparison operator (instead of === as today) and syntax highlighting and linting was not a standard. We just used simple text editors to write PHP at that time.
The "yoda style" syntax helped to avoid fatal typos in comparisons involving a variable:
$foo = false;
if ($foo = true) ...
silently results in true being assigned to variable $foo, which might not be the intention. (Also, the if is always true)
Whereas
$foo = false;
if (true = $foo) ...
results in a syntax error, saving you from a headache.

PHP executing header:location regardless IF statement parameters [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
The 3 different equals
Can anyone tell me why, when using the code below, I am getting redirected to elephant.com rather than seeing a 'giraffe!
<?php
$foo="giraffe";
if($foo="elephant"){
header("location:http://www.elephant.com");
exit();
}else{
echo $foo;}
?>
Thanks for looking
J
if($foo="elephant")
You're assigning $foo here, rather than comparing it; you should be doing:
if($foo=="elephant")
The result of an assignment operation is the value that's just been assigned; in this case, 'elephant' is evaluating to true.
Your if() statement has a single equal sign. This doesn't do a comparison in PHP; it sets the value and returns true.
In order to do a comparison, you need to use either a double-equal or a triple-equal sign:
if($foo == "elephant") { .... }
or
if($foo === "elephant") { .... }
The difference between the two is that double-equal doesn't care about the variable's data type, whereas triple-equal does. In this case, there's not much difference between them, but it's worth learning and understanding the differences because they can bite you if you don't know them. More info here: http://php.net/manual/en/language.operators.comparison.php

Order in conditional statements [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php false place in condition
I have noticed that a lot of PHP code uses conditional statements like CONST == VARIABLE. I grew up with the syntax always articulated in reverse. Is there a reason for this structure?
Example:
// this is the way I see it most typically represented in PHP
if ( false == $foobar ) { // do this }
// this is the way I normally do it
if ( $foobar == false ) { // do this }
This is to prevent a common typo between == and =, known as a yoda condition. Consider the following:
if( false = $foobar) {
This would result in an error, catching what would be considered a bug, since you cannot assign anything to false. On the contrary:
if( $foobar = false) {
This is valid syntax, and is quite an easy mistake to make.
However, I typically prefer the if( $foobar == false) syntax, as unit tests should be able to catch these programmatic mistakes.
The way you normally do it is exactly how most programmers do it. The first example is called a yoda condition:
http://www.dodgycoder.net/2011/11/yoda-conditions-pokemon-exception.html
and is not the norm.

php syntax: program flow control using the || operator [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP short circuit lazy evaluation, where is it in the php.net manual?
PHP “or” Syntax
I have seen people using the || operator as program flow control as follows:
function() || die("message");
where die("message"); will run if function() returns false. Furthermore, it seems to only work for die(); and exit(); else the interpreter will throw a "syntax error" message.
I'm wondering what this is called and where can I find documentation for its behaviour.
It's just a boolean OR expression. The usage is taking advantage of a behavior called short cutting, where if the first part of the expression evaluates to true, then the second half isn't evaluated because the OR expression is already true.
It's just logic OR. If function() returns true, then the rest of the expression is not evaluated.
This is due to OR / || being an operator with left precedence (see here: http://www.php.net/manual/en/language.operators.precedence.php) as the left is evaluated to be true, there is no point in evaluating the right side as the expression will always be true.

Where can I read about conditionals done with "?" and ":" (colon)? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
I've been doing conditionals with if/else or a year or so now. Looking at some new code, I'm seeing a conditional that appears to use ? and : instead of if and else. I'd like to learn more about this, but I am not sure what to google to find articles explaining how it works. How can I do it?
It's the Ternary Operator.
Basic usage is something like
$foo = (if this expressions returns true) ? (assign this value to $foo) : (otherwise, assign this value to $foo)
It can be used for more than assignment though, it looks like other examples are cropping up below.
I think the reason you see this in a lot of modern, OO style PHP is that without static typing you end up needing to be paranoid about the types in any particular variable, and a one line ternary is less cluttered than a 7 line if/else conditional.
Also, in deference to the comments and truth in naming, read all about the ternary operators in computer science.
That would be the conditional operator. It's pretty much a single line if/then/else statement:
if(someCondition){
$x = doSomething();
}
else{
$x = doSomethingElse();
}
Becomes:
$x = someCondition ? doSomething() : doSomethingElse();
It is:
condition ? do_if_true : do_if_false
So, for example in the below, do->something() will be run.
$true = 1;
$false = 0
$true ? $do->something() : $do->nothing();
But in the below example, do->nothing() will be run.
$false ? $do->something() : $do->nothing();
This is the ternary operator in PHP. It's shorthand for if/else, format is:
condition ? true expression : false expression;

Categories