If statement is true OR not false [duplicate] - php

This question already has answers here:
Is there a difference between !== and != in PHP?
(7 answers)
difference between != and !== [duplicate]
(4 answers)
The 3 different equals
(5 answers)
Closed 3 years ago.
I have two statements like this:
$ready = true;
if($ready === true) {
echo "it's ready!";
}
And this:
$ready = true;
if($ready !== false) {
echo "it's ready!";
}
I know those mean the same thing as === true and !== false is the same thing. I see people use the negation type (is not false or is not {something}). like this: https://stackoverflow.com/a/4366748/4357238
But what are the pros and cons of using one or the other? Are there any performance benefits? Any coding benefits? I would think it is confusing to use the negation type rather than the straight forward === true. Any input would be appreciated! thank you

These do not mean the same thing, and you can see this demonstrated below:
$ready = undefined;
if($ready === true) {
console.log("it's ready 1");
}
if($ready !== false) {
console.log("it's ready 2");
}
When in doubt, stick with ===. You're comparing to exactly what it should be. "This should exactly be equal to true" vs "This should be equal to anything but exactly false" are 2 separate statements, the second including a lot of values that would be true (As demonstrated above, undefined is not exactly false, so this would be true).

Most PHP functions return false as failure, such as strpos, from the manual it says:
Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So it returns an integer or false, then it is wrong to use strpos() === true
strpos() !== false is the right way to check the result.

It is not about performance and they are not the same. It helps us in reducing unnecessary if else statements.
Consider this: there is a variable foobarbaz whose value can be anything among foo/ bar/ baz/ foobar/ barbaz. You need to execute a statement if the value is not foo. So instead of writing like this:
if(foobarbaz === "bar" || foobarbaz === "baz" || foobarbaz === "foobar" || foobarbaz === "barbaz") {
//some statement
}
else if(foobarbaz === "foo") {
//do nothing
}
You can write something like this:
if(foobarbaz !== "foo") {
//some statement
}
You can see we were able to eliminate the unnecessary else statement.

In php == compare only the values are equal. For and example
$ready = 'true';
if($ready == true) {
echo "true";
}
else{
echo "false";
}
It print true.But if it is compare with === it not only check the values but also it check the datatype. So it compares with === it print the false.
Talking about !== it's work as the same. So it's not a problem to output if you use
if($ready === true)
or
if($ready !== false)
Can't compare these two because both are same.

Related

Why the array_search not matching? [duplicate]

This question already has answers here:
php array_search returning 0 for the first element?
(4 answers)
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Closed 5 years ago.
Why does example A fail, but example B work?
A) FAIL:
$request_IP = '8.8.8.8';
$list_Array = explode(',', "8.8.8.8,9.9.9.9,2.2.2.2");
$result = array_search($request_IP, $list_Array);
if($result) {
// Expecting - to get it success there
}
else {
echo "FAIL";
exit;
}
B) WORKS:
$request_IP = '8.8.8.8';
$list_Array = explode(',', "0,8.8.8.8,9.9.9.9,2.2.2.2");
$result = array_search($request_IP, $list_Array);
if($result) {
// In this case it works??
}
else {
echo "FAIL";
exit;
}
From the documentation for array_search:
Returns the key for needle if it is found in the array, FALSE otherwise.
So you should change your code to:
$result = array_search($request_IP, $list_Array);
if ($result === false) {
// Not found
echo "FAIL";
exit;
} else {
// $result is the key of the element in the array
echo $result . "\n";
}
Example A matches properly, it returns index 0.
0 is a falsy variable. 0 == false.
Look at https://secure.php.net/manual/en/types.comparisons.php what kind of values match to which result when doing loose comparisan(two ==) in the boolean column
You can better flip the if statements, to test for the false first.
We don't need an "else" here because either the code will abort in the if statement, or it will continue.
Saves an indentation level.
if($result === false) {
echo "FAIL";
exit;
}
// success
Three === means an exact match on value AND type
That's because in section A,
array_search($request_IP, $list_Array) will return zero.
so next condition line would compile as following:
if ($result) // if (0)
this condition will always return false.
To fix this issue. you have to use following line
if ($result === FALSE)
Because in your first example array_search will return 0 - because the first occurence of 8.8.8.8 is the first item. PHP is designed "weakly", so an assertion of "0" and boolean false will be true (false == 0) and an assertion of 1 and true will also be true (true == 1). This can be very tricky - as for example strpos returns 0 if a pattern is in the beginning of a string, in that case you would need to write your condition like (strpos($string, $search) !== false) - simply checking the return type "weakly" would result in a logic error (!strpos($string, $search).
You will have to adopt the condition.
I would recommend to use in_array
if (in_array($request_IP, $list_Array) === true)
will do
You should also have a look at this question:
What are the benefits (and drawbacks) of a weakly typed language?
Weak types is not bad design, its concept, if you use PHP or any other weakly typed language for business logic, you will need to be extra careful, using strict comparison only (=== instead of ==, !== instead of != and explicit comparison instead of negation) is a good start.

Does variables' order matter when doing == and === comparisons? [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 9 years ago.
Does it really matter to put variables after == or === when doing comparisons?
if (null == $var) {
}
if ($var == null) {
}
I've constantly seen coders prefer this way, is it for speed difference?
Updates:
Sorry I didn't make my question clear, what I want to know is not the different between == and ===, but expressions like null == $var and $var == null, so I've changed the code example.
Conslusion:
No functional or performance difference. Some consider it a best practice or simply a coding style. BTW it has a cool name: Yoda Conditions :)
FYI: PHP error messages use this style, e.g.
PHP Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)
Don't know why this question is marked duplicated to (The 3 different equals) not (What's the difference between 'false === $var' and '$var === false'?)
It prevents typos which cause very hard to debug bugs. That's in case you accidentally write = instead of ==:
if ($var == null) # This is true in case $var actually is null
if ($var = null) # This will always be true, it will assign $var the value null
Instead, switching them is safer:
if (null == $var) # True if $var is null
if (null = $var) # This will raise compiler (or parser) error, and will stop execution.
Stopping execution on a specific line with this problem will make it very easy to debug. The other way around is quite harder, since you may find yourself entering if conditions, and losing variable's values, and you won't find it easily.
I think that the following code will explain it:
echo (( 0 == NULL ) ? "0 is null" : "0 is not null") ."\n";
echo (0 === NULL) ? "0 is null" : "0 is not null" ;
it will output:
0 is null
0 is not null
The === operator checks for both value and type, but 0 is a number while NULL is of type NULL
The == operator checks only for value and zero can be casted to "false" or "null" hence the "truthy" that we get for the first line
Compare results from this to ifs.
echo "Test '1abc' == 1 - ";
if ('1abc' == 1) {
echo 'ok';
} else {
echo 'fail';
}
echo "\nTest '1abc' === 1 - ";
if ('1abc' === 1) {
echo 'ok';
} else {
echo 'fail';
}
Then read this page http://php.net/manual/en/language.types.type-juggling.php it's very interesting lecture ;)

What may go wrong if I don't use === or !== in PHP [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php == vs === operator
Is there a difference between !== and != in PHP?
In PHP, the condition of the if command contains operator === and !==.
I never use them. So I wonder when will we actually need to call them?
E.g.
if (FALSE != someMethod() ) {
}
if (FALSE !== someMethod() ) {
}
What may go wrong with the 1st if?
0 == '' == null == false == array()
If you need to know the difference between two of these, you need ===.
http://php.net/manual/en/function.strpos.php
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
strpos('apple', 'a') == 0
strpos('apple', 'b') == false
Without a === you won't know if 'apple' has 'a' in the first position or if it doesn't exist.
Take an example like this:
$str = '*Hello*World*';
if (FALSE != strpos($str, '*')){
// Echo if string has an '*' in it!
echo $str;
}
This won't work, because strpos() returns the index of the first match. In this case it returns 0. FALSE == 0, but FALSE !== 0.
PHP uses loose comparison when you use == and !=' instead of===and '!==. Loose comparison means, that types are compared on 'similarity'. To get an overview of how types compare, look here

PHP: Are these statements equivalent? (file_exists())

Aren't these equivalent?
==SCRIPT A==
if (file_exists($file) == false) {
return false;
}
==SCRIPT B==
if(!file_exists($file)) {
return false;
}
Plain answer: Y E S
They evaluate to the same thing.
That first one might be even better suited like this:
if (file_exists($file) === false) { // === checks type and value
return false;
}
OR:
return file_exists($file);
yes, file_exists returns a boolean, so it's either true or false.
so you could return file_exists($file) as well...
If you are making boolean comparisons, then you would rather do this:
if (file_exists($file) === false) {
return false;
}
using the === operator, to ensure that what you are receiving is a variable of type boolean and of value equivalent to false.
Yes.
But if you would use:
if (file_exists($file) === false) {
return false;
}
then it would not be the same as:
if(!file_exists($file)) {
return false;
}
because in the first case it would check whether the value returned by function matches strictly to false, and in the second case the value returned by function would be evaluated to boolean value.
EDIT:
That is general rule.
But in case of file_exists() function, which returns boolean value, evaluating to boolean is not necessary, thus you can use strict condition and this will have the same result (but only in case you know the value will be either true or false.
If you're asking "what's the difference between the === and == operator" then:
'===' is a strict comparison that checks the types of both sides.
'==' is an 'equivalent to' comparison operator that will cast either side to the appropriate type if deemed necessary.
To expand, '==' can be used to check for 'falsey' values and '===' can be used to check for exact matches.
if (1 == TRUE) echo 'test';
>> "test"
if (1 === TRUE) echo 'test';
>>
If you're asking if there's any functional / practical difference between your two code blocks then no, there isn't and you should be returning as such: return file_exists($file);
Worth a read:
http://php.net/manual/en/language.operators.comparison.php

Does PHP have short-circuit evaluation?

Given the following code:
if (is_valid($string) && up_to_length($string) && file_exists($file))
{
......
}
If is_valid($string) returns false, does the php interpreter still check later conditions, like up_to_length($string)?
If so, then why does it do extra work when it doesn't have to?
Yes, the PHP interpreter is "lazy", meaning it will do the minimum number of comparisons possible to evaluate conditions.
If you want to verify that, try this:
function saySomething()
{
echo 'hi!';
return true;
}
if (false && saySomething())
{
echo 'statement evaluated to true';
}
Yes, it does. Here's a little trick that relies on short-circuit evaluation. Sometimes you might have a small if statement that you'd prefer to write as a ternary, e.g.:
if ($confirmed) {
$answer = 'Yes';
} else {
$answer = 'No';
}
Can be re-written as:
$answer = $confirmed ? 'Yes' : 'No';
But then what if the yes block also required some function to be run?
if ($confirmed) {
do_something();
$answer = 'Yes';
} else {
$answer = 'No';
}
Well, rewriting as ternary is still possible, because of short-circuit evaluation:
$answer = $confirmed && (do_something() || true) ? 'Yes' : 'No';
In this case the expression (do_something() || true) does nothing to alter the overall outcome of the ternary, but ensures that the ternary condition stays true, ignoring the return value of do_something().
Bitwise operators are & and |.
They always evaluate both operands.
Logical operators are AND, OR, &&, and ||.
All four operators only evaluate the right side if they need to.
AND and OR have lower precedence than && and ||. See example below.
From the PHP manual:
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f before the "or" operation occurs
// Acts like: (($f = false) or true)
$f = false or true;
In this example, e will be true and f will be false.
Based on my research now, PHP doesn't seem to have the same && short circuit operator as JavaScript.
I ran this test:
$one = true;
$two = 'Cabbage';
$test = $one && $two;
echo $test;
and PHP 7.0.8 returned 1, not Cabbage.
No, it doesn't anymore check the other conditions if the first condition isn't satisfied.
I've create my own short-circuit evaluation logic, unfortunately it's nothing like javascripts quick syntax, but perhaps this is a solution you might find useful:
$short_circuit_isset = function($var, $default_value = NULL) {
return (isset($var)) ? : $default_value;
};
$return_title = $short_circuit_isset( $_GET['returntitle'], 'God');
// Should return type 'String' value 'God', if get param is not set
I can not recall where I got the following logic from, but if you do the following;
(isset($var)) ? : $default_value;
You can skip having to write the true condition variable again, after the question mark, e.g:
(isset($super_long_var_name)) ? $super_long_var_name : $default_value;
As very important observation, when using the Ternary Operator this way, you'll notice that if a comparison is made it will just pass the value of that comparison, since there isn't just a single variable. E.g:
$num = 1;
$num2 = 2;
var_dump( ($num < $num2) ? : 'oh snap' );
// outputs bool 'true'
My choice: do not trust Short Circuit evaluation in PHP...
function saySomething()
{
print ('hi!');
return true;
}
if (1 || saySomething())
{
print('statement evaluated to true');
}
The second part in the condition 1 || saySomething() is irrelevant, because this will always return true. Unfortunately saySomething() is evaluated & executed.
Maybe I'm misunderstood the exact logic of short-circuiting expressions, but this doesn't look like "it will do the minimum number of comparisons possible" to me.
Moreover, it's not only a performance concern, if you do assignments inside comparisons or if you do something that makes a difference, other than just comparing stuff, you could end with different results.
Anyway... be careful.
Side note: If you want to avoid the lazy check and run every part of the condition, in that case you need to use the logical AND like this:
if (condition1 & condition2) {
echo "both true";
}
else {
echo "one or both false";
}
This is useful when you need for example call two functions even if the first one returned false.

Categories