PHP false-positives [duplicate] - php

This question already has answers here:
The 3 different equals
(5 answers)
Closed 8 years ago.
So I have this function and I'm trying to understand how this is true and how it comes out false if I use === instead of == .
function is_equal($value1, $value2) {
$output = "{$value1} == {$value2}: ";
if ($value1 == $value2) {
$output = $output . "true<br />";
} else {
$output = $output . "false<br />";
}
return $output;
}
echo is_equal("123", " 123");
echo is_equal("123", "+0123");
?>
this code above comes out true because I'm testing for == how is that? and also if I use === it's false

When you compare equality using ==, PHP will juggle the types. I suspect your types are being juggled resulting in a numeric comparison.
When you compare equality using === the type is compared first, followed by the values.

Yes, this is right. === will compare the value and the typeinstead of == that is comparing if values are identical.
You can also try this one :
echo is_equal("123", 123);

=== tests whether the two variables are identical (same value, same type). == tests for equality and does type juggling for you.
Read up over here.

Related

If statement is true OR not false [duplicate]

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.

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.

PHP !== operator [duplicate]

This question already has answers here:
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Closed 5 years ago.
I'm new to PHP and unfamiliar with the !== and === operators. Are Logic #1 and #2 below equivalent? And if not, why so? Basically, the code reads values from a csv row in a file, and if the value is empty it disregards empty or null values
//Logic #1
$value = readValue();
//skip empty values
if ( !$value || $value === '') {
print "empty value found";
}else{
doSomething();
}
//Logic #2
$value = readValue();
if ( $value && $value !== '' ) {
doSomething();
}else{ //skip empty values
print "empty value found";
}
To answer your question about the == and === operators, those should be identical.
== is the opposite of !=
=== is the opposite of !==
See this previous answer for more information on the difference between == and ===.
To improve your code a bit, I would suggest using the empty() function which will check for nulls and empty strings.
Something like this:
if (empty($value)) echo "nothing to see here";
else doSomething();

symbols == 0 true in php [duplicate]

This question already has an answer here:
symbol and decimal number true in php
(1 answer)
Closed 8 years ago.
I have script like this
if('#' == 0){
echo "true";
}else{
echo "false";
}
output :
true
the question is why it get true and how to get it false?
thanks.
As Mark Baker stated in the comments, PHP uses weak typing. According to the comparison matrix that you find here (http://www.php.net/manual/en/types.comparisons.php), the expression involving the string '#' compared to 0 will be evaluated as true.
Change your condition to:
if('#' === 0){
...
in this case you'll get false.
For this condition to get true of false properly, you need to compare the value and the type of the operators. Try this:
if('#' === 0){
echo "true";
}else{
echo "false";
}
You will get false for this case.

Strange logic behaviour in PHP - is this normal?

Can anyone figure out why this might happen in PHP (am using v5.4):
$value = 0;
$existing_value = "Unknown";
if ($value == $existing_value) {
echo "$value == $existing_value";
} else {
echo "$value != $existing_value";
}
This outputs as 0 == Unknown
Interestingly, $value = "0" (i.e. set as a string), evaluates to be false
Is this a known behaviour? Have I missed something in the documentation on this? Debugging this was driving me crazy earlier today!
Thanks for your help in advance...
This is caused by the automatic type casting, PHP uses.
When comparing an int value with a string using just ==, the string will be casted to an int, which in your case results in a 0 and hence a true evaluation.
See the respective PHP documentation for more information.
To circumvent this, you could use === instead of ==. The former includes a type check, which will make your condition evaluate to false:
$value = 0;
$existing_value = "Unknown";
if ($value === $existing_value) {
echo "$value === $existing_value";
} else {
echo "$value !== $existing_value";
}
When you compare a number with a string in PHP, as you do here, the string is converted to a number. Since the string "Unknown" is not numeric, it's converted to the number 0.
If you check for equality with the === operator, it won't perform type conversion and it'll evaluate as false.
http://php.net/manual/en/language.operators.comparison.php
You should have a look at the comparison tables in PHP Especially the loose comparison (using ==) section as compared to the strict comparison (using ===) section.

Categories