Pages

Thursday, July 5, 2012

Know the Difference Between Comparison Operators


This is a good tip, but it is missing a practical example that demonstrates when a non-strict comparison can cause problems.
If you use strpos() to determine whether a substring exists within a string (it returns FALSE if the substring is not found), the results can be misleading:
<?php
 
$authors = 'Chris & Sean';
 
if (strpos($authors, 'Chris')) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}
 
?>
Because the substring Chris occurs at the very beginning of Chris & Sean, strpos() correctly returns 0, indicating the first position in the string. Because the conditional statement treats this as a Boolean, it evaluates to FALSE, and the condition fails. In other words, it looks like Chris is not an author, but he is!
This can be corrected with a strict comparison:
<?php
 
if (strpos($authors, 'Chris') !== FALSE) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}
 
?>

0 comments:

Post a Comment