Thursday, 10 August 2017

Know the Difference Between Comparison Operators

Know the Difference Between Comparison Operators

This is a decent tip, however it's missing a sensible example that demonstrates once a non-strict comparison will cause issues.

If you employ strpos() to see whether or not a substring exists at intervals a string (it returns FALSE if the substring isn't found), the results may 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 happens at the terribly starting of Chris &amp; Sean, strpos() properly returns zero, indicating the primary position within the string. as a result of the conditional statement treats this as a Boolean, it evaluates to FALSE, and also the condition fails. In alternative words, it's like Chris isn't associate degree 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.';
}


?>


No comments:

Post a Comment

HTML APIs: What They Are And How To Design A Good One

As JavaScript developers, we regularly forget that not everybody has a similar data as USA. It’s referred to as the curse of knowledge:...