• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

PHP function strcmp() – Binary safe string comparison

by admin

The strcmp() function is used to compare two case-sensitive strings. This function was introduced in PHP3. The function basically compares two strings; returns a number less than 0 if one is less than two, 0 if the two strings are equal, and a number greater than 0 if one is greater than two. The comparison is case-sensitive—that is, “Alphabet” and “alphabet” are not considered equal.

Syntax:

strcmp(string $string1, string $string2): int

Parameters

Parameter Description
string1 The first string.
string2 The second string.

Return Values

Returns < 0 if string1 is less than string2; > 0 if string1 is greater than string2, and 0 if they are equal.

Examples

Example 1:

$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;
}

Example 2:

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcmp($var1, $var2) !== 0) {
    echo '$var1 is not equal to $var2 in a case sensitive string comparison';
}
?>

Final Thoughts

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 afterword two, or 0 if word one and word two are the same.

Filed Under: PHP

Some more articles you might also be interested in …

  1. PHP function strlen() – Get string length
  2. PHP function acos – Arc cosine
  3. PHP function stripslashes() – Un-quotes a quoted string
  4. PHP function chr() – Generate a single-byte string from a number
  5. PHP addslashes function – Quote string with slashes
  6. PHP cos function – Cosine
  7. PHP Function str_split() – Convert a string to an array
  8. PHP function convert_cyr_string() – Convert from one Cyrillic character set to another
  9. PHP atanh function – Inverse hyperbolic tangent
  10. htaccess Cheatsheet

You May Also Like

Primary Sidebar

Recent Posts

  • powertop Command Examples in Linux
  • powertop: command not found
  • powerstat: command not found
  • powerstat Command Examples in Linux

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright