Skip to content

Ignore case sensitivity when comparing strings in PHP

In PHP, you can use the strcasecmp() function to compare two strings and ignore case sensitivity. This function returns 0 if the two strings are equal, a negative value if the first string is less than the second, and a positive value if the first string is greater than the second. Here's an example:

Example of using the strcasecmp() function to compare two strings and ignore case sensitivity in PHP

php
<?php

$string1 = "Hello";
$string2 = "hello";

if (strcasecmp($string1, $string2) == 0) {
    echo "The strings are equal.";
} else {
    echo "The strings are not equal.";
}

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

This will output "The strings are equal." because the strcasecmp() function ignores the case of the characters in the strings.

Another way is using strcmpi() function for case-insensitive comparison:

Example of using the strcmpi() function to compare two strings and ignore case sensitivity in PHP

php
<?php

$string1 = "Hello";
$string2 = "hello";

if (strcmpi($string1, $string2) == 0) {
    echo "The strings are equal.";
} else {
    echo "The strings are not equal.";
}

Note that, strcmpi() function is not available in PHP, you can use strcasecmp() instead of it.

Dual-run preview — compare with live Symfony routes.