Zen Cart Logo
Forums / Contribution-Writing Guidelines / Testing for equality in your PHP script? Take care!

Testing for equality in your PHP script? Take care!

Locked

Views: 1,707

Results 1 to 4 of 4
This thread is locked. New replies are disabled.
26 Jan 2013, 12:09 PM
#1
swguy avatar

swguy

Administrator

Join Date:
Feb 2006
Location:
Tampa Bay, Florida
Posts:
10,693
Plugin Contributions:
56

Testing for equality in your PHP script? Take care!

Do you know what this program outputs?

<?php
$i = 0;
$j = 'test string';
if ($i == $j) { 
   echo 'equal';
} else {
   echo 'not equal';
}

This is how PHP works. Complaining is futile, as this developer discovered:
https://bugs.php.net/bug.php?id=39579

26 Jan 2013, 12:53 PM
#2
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,083
Plugin Contributions:
56

Re: Testing for equality in your PHP script? Take care!

Answer: equal. It got me, too, recently!

26 Jan 2013, 12:57 PM
#3
swguy avatar

swguy

Administrator

Join Date:
Feb 2006
Location:
Tampa Bay, Florida
Posts:
10,693
Plugin Contributions:
56

Re: Testing for equality in your PHP script? Take care!

Yes, in fact it was your submission and the reference to this bug report that motivated me to make this post. Thanks for documenting your findings so others will learn!

30 Jan 2013, 4:55 AM
#4
rodg avatar

rodg

Deceased

Join Date:
Jan 2007
Location:
Australia
Posts:
6,263
Plugin Contributions:
4

Re: Testing for equality in your PHP script? Take care!

swguy:

Do you know what this program outputs?

<?php $i = 0; $j = 'test string'; if ($i == $j) { echo 'equal'; } else { echo 'not equal'; } ``` > > This is how PHP works. Complaining is futile, as this developer discovered: > <https://bugs.php.net/bug.php?id=39579> Personally I don't see why this is being called a bug. If you think about it, it doesn't make sense to compare a number variable with a string variable in the first place, so even if any given programming language does allow it (such as PHP) the results will be somewhat unpredictable. Most programming languages will treat/trap this as an error. As much as I like PHP, I find that it's not a good programming language to learn from, simply because it **does** allow loose typecasting, which teaches bad coding habits that will invariably cause this type of unexpected behaviour at times. Just my 2cents worth. Cheers Rod