Jump to content

equality/inequality testing


AP81

Recommended Posts

Hi,

 

Take a look at the following code below:

<?php
$test = true;

if ($test == true) {
echo "true";
} else {
echo "false";
}
?>

 

Now that looks fine to me.  I was reading a book which suggests to always put the constant on the left hand side of an equality/inequality comparison.  So the above would become:

<?php
$test = true;

if (true == $test) {
echo "true";
} else {
echo "false";
}
?>

 

 

The reason is that if you leave out one of the = signs, the parser will find the error for you.

 

So this script still runs:

 

<?php

$test = true; 

if ($test = true) { // removed one equals sign
echo "true";
} else {
echo "false";
}
?>

 

And the following fails:

<?php

$test = true; 
if (true = $test) { // removed one equals sign
echo "true";
} else {
echo "false";
}
?>

 

So I can see some merit in this, but it just doesn't look right to me.  Most people I know would put the constant on the right hand side, as it seems more logical.

 

What are your thoughts on this?

Link to comment
https://forums.phpfreaks.com/topic/111038-equalityinequality-testing/
Share on other sites

IMO, I do not think that's necessary. instead, you can use:

 

<?php
$test = true; 

if ($test) { 
echo "true";
} else {
echo "false";
}
?>

 

its neater and parsed perfectly, why? because conditional statements eats boolean... equating a boolean with another boolean is unnecessary.

Just get in the habit of using double equals signs. When I was still a complete noobie, I had a giant if/elseif statement with about 30 cases (not knowing about switch statements *rollseyes*) and they all had a single equals sign, so the last or first condition or something like that was always selected no matter what I gave the code. Ever since then, I've never forgotten an equals sign on a comparison test.

 

Dan

IMO, I do not think that's necessary. instead, you can use:

 

<?php
$test = true; 

if ($test) { 
echo "true";
} else {
echo "false";
}
?>

 

its neater and parsed perfectly, why? because conditional statements eats boolean... equating a boolean with another boolean is unnecessary.

 

That's not what he was getting at.  For example:

You needed $foo to be equal to 2 to do something.

if ($foo == 2) {
} else {
}

 

Good.  Now what if you accidentally did:

if ($foo = 2) {
} else {
}

The IF would always execute because you're setting $foo equal to 2.  This may not look incorrect among hundreds of lines of code.  But, if you wrote your conditionals as:

if (2 = $foo) {
} else{
}

 

You can't assign anything to a constant, so it'll error out and you'll know where you went wrong.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.