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();
Related
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.
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.
This question already has answers here:
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Closed 9 years ago.
In my case should I use != as below, or is !== more appropriate, what is the difference.
private function authenticateApi($ip,$sentKey) {
$mediaServerIp = '62.80.198.226';
$mediaServerKey = '45d6ft7y8u8rf';
if ($ip != $mediaServerIp ) {
return false
}
elseif ($sentKey != $mediaServerKey ) {
return false
}
else {
return true;
}
}
public function setVideoDeletedAction(Request $request)
{
//Authenticate sender
if ( $this->authenticateApi($request->server->get("REMOTE_ADDR"),$request->headers->get('keyFile')) != true ) {
new response("Din IP [$ip] eller nyckel [********] är inte godkänd för denna åtgärd.");
}
!= checks value
if($a != 'true')
!== checks value and type both
if($a !== 'true')
http://www.php.net/manual/en/language.operators.comparison.php
As the manual says, one compares type as well.
!== is more strict. '1'==1 returns true, but '1'===1 - false, because of different types.
=== and !== are used to compare objects that might be of different type. === will return TRUE iff the types AND values are equal; !== will return TRUE if the types OR values differ. It is sometimes known as the 'congruency' operator.
If you are comparing two things that you know will always be the same type, use !=.
Here's an example of using !==. Suppose you have a function that will return either an integer or the value FALSE in the event of a failure. 0 == FALSE, but 0 !== FALSE because they are different types. So you can test for FALSE and know an error happened, but test for 0 and know you got a zero but no error.
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 ;)
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?
I know the basic difference between == and === , but can some experienced coders tell me some practical examples for both cases?
== checks if the values of the two operands are equal or not. === checks the values as well as the type of the two operands.
if("1" == 1)
echo "true";
else
echo "false";
The above would output true.
if("1" === 1)
echo "true";
else
echo "false";
The above would output false.
if("1" === (string)1)
echo "true";
else
echo "false";
The above would output true.
Easiest way to display it is with using strings. Two examples:
echo ("007" === "7" ? "EQUAL!" : "not equal");
echo ("007" == "7" ? "EQUAL!" : "not equal");
In addition to #DavidT.'s example, a more practical example is the following:
$foo = "Goo";
$bar = "Good Morning";
if (strpos($bar,$foo))
echo "Won't be seen, returns false because the result is in fact 0";
if (strpos($bar,$foo) !== false)
echo "True, though 0 is returned it IS NOT false)";