Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

strcmp()

Synopsis

    int strcmp ( string str1, string str2 )

The strcmp() function, 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.

    $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.

If the only difference between your strings is the capitalization of letters, you should know that capital letters come before their lowercase equivalents. For example, "PHP" will come before "php."

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page