Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

strcmp

Compares two strings.

Syntax

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

Parameters

ParameterTypeDescription
$string1stringThe first string.
$string2stringThe second string.

Return value

intA negative number if the first string is smaller, a positive one if larger, `0` if they are equal.

Examples

The result of a comparison:

<?php
 
echo strcmp('apple', 'banana'), ' ', strcmp('apple', 'apple'), ' ', strcmp('b', 'a');

Output:

-1 0 1

Sorting strings alphabetically:

<?php
 
$names = ['Oleg', 'Anna', 'Ivan'];
 
usort($names, 'strcmp');
 
echo implode(', ', $names);

Output:

Anna, Ivan, Oleg

Notes

The comparison is case-sensitive: uppercase letters come before lowercase ones. strcasecmp() compares ignoring case.

See also

  • usort — Sorts an array by a custom comparison rule.
  • strtolower — Converts ASCII letters to lowercase.

Related recipes

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.