strcmp
Compares two strings.
Syntax
strcmp(string $string1, string $string2): intParameters
| Parameter | Type | Description |
|---|---|---|
| $string1 | string | The first string. |
| $string2 | string | The 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 1Sorting strings alphabetically:
<?php
$names = ['Oleg', 'Anna', 'Ivan'];
usort($names, 'strcmp');
echo implode(', ', $names);Output:
Anna, Ivan, OlegNotes
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.