• 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 base_convert function – Convert a number between arbitrary bases
  2. PHP asin function – Arc sine
  3. PHP Function strchr() – Alias of strstr()
  4. PHP function str_repeat() – Repeat a string
  5. How to test a PHP script
  6. PHP function str_replace() – Replace all occurrences of the search string with the replacement string
  7. PHP Function str_word_count() – Return information about words used in a string
  8. PHP function chunk_split() – Split a string into smaller chunks
  9. “Access denied for user ‘username’@’hostname’ (using password: YES)” – Error while connecting MySQL with PHP
  10. PHP cos function – Cosine

You May Also Like

Primary Sidebar

Recent Posts

  • JavaFX ComboBox: Set a value to the combo box
  • Nginx load balancing
  • nginx 504 gateway time-out
  • Images preview with ngx_http_image_filter_module

© 2022 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright