Check If A String Is A Palindrome In PHP
Code snippet for how to Check If A String Is A Palindrome In PHP with sample and detail explanation
Identifying if a given string is a palindrome is a common coding challenge in many aspects of computer programming. In this article, we will detail how you can easily determine if a string is a palindrome using PHP.
Code snippet: Palindrome String Checker
Below is a simple PHP function that checks if a provided input string is a palindrome or not.
function isPalindrome($string)
{
//Removing special characters from the string and converting it to lower case
$cleanString = strtolower(preg_replace("/[^A-Za-z0-9]/", '', $string));
// reversing the cleaned string
$reversedString = strrev($cleanString);
// checking the equality between the cleaned string and the reversed string
return $cleanString == $reversedString;
}
You can use this function like so:
echo isPalindrome('Was it a car or a cat I saw?'); //outputs: 1 which means it's true
echo isPalindrome('Hello world'); //outputs nothing as it's false
Code Explanation: Palindrome String Checker
Let’s break down the function isPalindrome($string)
with the step-by-step explanation:
- The first step in the function is to clean the input string. Many times, when dealing with sentences or phrases, the strings often contain spaces, punctuation, or varied capitalization which might affect whether the input is considered a palindrome. So, we use
strtolower()
to change all characters to lowercase andpreg_replace()
to remove any unwanted characters excluding alphanumerics.
$cleanString = strtolower(preg_replace("/[^A-Za-z0-9]/", '', $string));
- Next, the function reverses the cleaned string using the PHP function
strrev()
which happens to reverse strings.
$reversedString = strrev($cleanString);
- Finally, it examines if the cleaned, original string equals the reversed string. If it is, this means that the string is a palindrome and the function will return 1 (true), otherwise, it won’t output anything as it’s false.
return $cleanString == $reversedString;
That’s it! With this simple explanation, you should be able to understand and implement the PHP function to check if a string is a palindrome.