extrovertive Posted October 14, 2006 Share Posted October 14, 2006 I know strcmp returns 0 if both string are the same -1 is string a is < b 1 is a > b.But what are some practical uses of it in an application? Link to comment https://forums.phpfreaks.com/topic/23924-uses-of-the-strcmp-function/ Share on other sites More sharing options...
.josh Posted October 14, 2006 Share Posted October 14, 2006 i found this comment in the strcmp section of the manual, which seems to be a good explanation:[quote]One thing to note in comparison with ==When we make a comparison with == php automaticly converts strings to integers when either side of the comparison is an integer, f.e.:<?$value = 0;if($value == "submit") { echo "Let's submit";}?>Above would be succesful, since "submit" is converted to an integer (eq 0) and the equation is would return true; (that's why (1 == "1submit") would also return true)That's why we should use strcmp or === (checks type also), for string comparisons.So my conclusion is that when comparing string, you'd better not make use of == (use strmp or === instead). For integer comparisons the == equation can be usefull, since our values will always be casted to an integer (1 == "1" returns true).[/quote] Link to comment https://forums.phpfreaks.com/topic/23924-uses-of-the-strcmp-function/#findComment-108722 Share on other sites More sharing options...
extrovertive Posted October 14, 2006 Author Share Posted October 14, 2006 Ah, I see. I've been using if($data == 'mystring') the whole time; should've use === instead.But, if the string is the same, why return 0? What's the -1 and 1 for in the comparison? Link to comment https://forums.phpfreaks.com/topic/23924-uses-of-the-strcmp-function/#findComment-108745 Share on other sites More sharing options...
.josh Posted October 14, 2006 Share Posted October 14, 2006 because it's a binary comparison. it breaks the strings down to their binary equivelants and compares them. Therefore it needs 3 returnable values: less than, equal or greater than. [code]strcmp(101,100); //returns 1 because 101 is greater than 100strcmp(101,101); //returns 0 because they are equalstrcmp(1010,1011); //returns -1 becuase 1010 is less than 1011[/code] Link to comment https://forums.phpfreaks.com/topic/23924-uses-of-the-strcmp-function/#findComment-108823 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.