Re: comparing a string

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Rafael wrote:
(inline)

Adam Zey wrote:
Rafael wrote:
A single "=" it's an assignment, not a comparison; and though it sometimes work, you shouldn't compare strings with "==", but using string functions, such as strcmp()... or similar_text(), etc.

This is PHP, not C. Operators such as == support strings for a reason, people should use them as such.

You shouldn't rely on what other languages do, but the one you're working with; PHP has no explicit data-types and manages strings as PERL does. Just as you say there's a reason why "==" supports strings, there's also a reason (or more) for strcmp() to exists --it's just safer to use strcmp() instead of "==", e.g: 24 == "24/7"

Safer, yes. And it'd be even better to do 24 === "24/7", in which case you don't need a function call, it's probably faster (I'd imagine that comparing equality is faster than finding out HOW close it is like strcmp does), and as I mentioned, easier to read.


If you need to ensure type, (so that 0 == "foo" doesn't return true), then you can use ===.

Using a function call that does more than you need when there is an operator to achieve the same goal is bad advice.

I think you haven't encounter a "special case" to make you understand "==" does NOT have the same behaviour as strcmp() It's just like the (stranger) case of the loop
  for ( $c = 'a';  $c <= 'z';  $c ++ )
      echo  $c;

I didn't say that it had the same behaviour, only the same goal; finding out if two strings are equal. strcmp does MORE than that, it also finds out how CLOSE they are. You almost never need that information, in which case you're wasting processing time with a function call that does something that you don't need. Come on, face it, how many times have done anything with strcmp's return value OTHER than checking that it's zero? I bet the cases are fairly rare.


Not to mention the fact that it leads to harder to read code. Which of these has a more readily apparent meaning?

if ( strcmp($foo,$bar) == 0 )

if ( $foo === $bar )

That might be true, either way you need to know the language to understand what the first line does and that the second isn't a typo.

=== is a basic operator. One has to assume that somebody writing code is at least familiar with the basic operators. If not, well, asking them to know what the function strcmp does and what it means when it returns zero is just as onerous. If not more so. And again, strcmp wastes time calculating information we don't NEED.

Regards, Adam.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux