Hudzilla.org - the homepage of Paul Hudson
Contents > Functions > Playing with strings Wish List | Report Bug | About Me ]

4.7.15     Comparing strings: strcmp() and strcasecmp()

This is NOT the latest copy of this book; click here for the latest version.

int strcmp ( string str1, string str2)

int strcasecmp ( string str1, string str2)

Strcmp(), and its case-insensitive sibling strcasecmp(), is a quick way of comparing two words and telling whether they are equal, or whether one comes before the other. It takes two words for its two parameters, and returns -1 if word one comes alphabetically before word two, 1 if word one comes alphabetically after word two, or 0 if word one and word two are the same.

<?php
    $string1
= "foo";
    
$string2 = "bar";
    
$result = strcmp($string1, $string2);

    switch (
$result) {
        case -
1: print "Foo comes before bar"; break;
        case
0: print "Foo and bar are the same"; break;
        case
1: print "Foo comes after bar"; break;
    }
?>

It is not necessary for us to see that "foo" comes after "bar" in the alphabet because we already know it does, however you would not bother running strcmp() if you already knew the contents of the strings - it is most useful when you get unknown input and you want to sort it.

As you can see, strcmp() can serve in place of == because it returns 0 when two strings are equal. There is an urban myth amongst PHP programmers that == is faster than strcmp(), however the reality is that it is just as fast, and you can use the two interchangeably if you wish. One thing, though: using ==, you get a "1" if two strings match, whereas with strcmp() you get a 0, so be careful!





<< 4.7.14 Removing HTML from a string: strip_tags()   4.7.16 Padding out a string: str_pad() >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Jajta / jaja@morroncrack.de.vu - 08 Sep 2008

supa!!!!



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is six plus eight?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow