In PHP, how do I compare strings with built-in functions?

In PHP, you can compare strings using several built-in functions. Here are some of the most commonly used functions:

  • strcmp() - Compares two strings and returns 0 if they are equal, a negative value if the first is less than the second, and a positive value if the first is greater than the second.
  • strcasecmp() - Performs a case-insensitive string comparison.
  • strpos() - Finds the position of the first occurrence of a substring in a string, which can be used for checking existence.
  • str_contains() - Checks if a string contains a specific substring (available in PHP 8.0 and later).

Here is an example of how to use these functions to compare strings:

<?php $string1 = "Hello, World!"; $string2 = "hello, world!"; // strcmp example if (strcmp($string1, $string2) === 0) { echo "The strings are identical."; } else { echo "The strings are not identical."; } // strcasecmp example if (strcasecmp($string1, $string2) === 0) { echo "The strings are identical (case insensitive)."; } else { echo "The strings are not identical (case insensitive)."; } // strpos example if (strpos($string1, "World") !== false) { echo "'World' found in string1."; } // str_contains example (PHP 8.0+) if (str_contains($string1, "Hello")) { echo "'Hello' found in string1."; } ?>

PHP string comparison strcmp strcasecmp strpos str_contains