Comparing Two Strings with strcmp() in PHP

Q

How To Compare Two Strings with strcmp()?

✍: FYIcenter.com

A

PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. But if you want to get an integer result by comparing two strings, you can the strcmp() function, which compares two strings based on ASCII values of their characters. Here is a PHP script on how to use strcmp():

<?php
$a = "PHP is a scripting language.";
$b = "PHP is a general-purpose language.";
print('strcmp($a, $b): '.strcmp($a, $b)."\n");
print('strcmp($b, $a): '.strcmp($b, $a)."\n");
print('strcmp($a, $a): '.strcmp($a, $a)."\n");
?>

This script will print:

strcmp($a, $b): 1
strcmp($b, $a): -1
strcmp($a, $a): 0

As you can see, strcmp() returns 3 possible values:

  • 1: The first string is greater than the section string.
  • -1: The first string is less than the section string.
  • 0: The first string is equal to the section string.

 

PHP Built-in Functions for Strings

⇒⇒PHP Tutorials

2016-10-13, 232👍, 0💬