PHP Program - Check whether a String is Palindrome or not
A string is known as a Palindrome string if the reverse of the string is same as the string. For example, 'radar' is a palindrome string, but 'rubber' is not a palindrome string.
Method 1: Check Palindrome String
In the example below, the string called MyString is checked for palindrome string. A while loop is used to compare the characters of the string. Two variables l and r are created which initially points to first and last character of the string. If the compared characters are not same, it will increase the variable flag by one and exit the loop, else the loop is continued. After each iteration, l is increased by one and r is decreased by one until they cross each other. Finally, based on value of flag variable, MyString is checked for palindrome string.
<?php function Palindrome($MyString) { $l = 0; $r = strlen($MyString) - 1; $flag = 0; while($r > $l){ if ($MyString[$l] != $MyString[$r]){ $flag = 1; break; } $l++; $r--; } if ($flag == 0){ echo $MyString." is a Palindrome string.\n"; } else { echo $MyString." is not a Palindrome string.\n"; } } Palindrome("radar"); Palindrome("rubber"); Palindrome("malayalam"); ?>
The above code will give the following output:
radar is a Palindrome string. rubber is not a Palindrome string. malayalam is a Palindrome string.
Method 2: Using PHP strrev() function
The same can be achieved by using PHP strrev() function.
<?php function Palindrome($MyString) { $revString = strrev($MyString); if ($revString == $MyString){ echo $MyString." is a Palindrome string.\n"; } else { echo $MyString." is not a Palindrome string.\n"; } } Palindrome("radar"); Palindrome("rubber"); Palindrome("malayalam"); ?>
The above code will give the following output:
radar is a Palindrome string. rubber is not a Palindrome string. malayalam is a Palindrome string.
Recommended Pages
- PHP Program - To Check Prime Number
- PHP Program - Bubble Sort
- PHP Program - Selection Sort
- PHP Program - Maximum Subarray Sum
- PHP Program - Reverse digits of a given Integer
- PHP - Swap two numbers
- PHP Program - Fibonacci Sequence
- PHP Program - Insertion Sort
- PHP Program - Find Factorial of a Number
- PHP Program - Find HCF of Two Numbers
- PHP Program - Merge Sort
- PHP Program - Shell Sort
- Stack in PHP
- Queue in PHP
- PHP Program - Find LCM of Two Numbers
- PHP Program - To Check Armstrong Number
- PHP Program - Counting Sort
- PHP Program - Radix Sort
- PHP Program - Find Largest Number among Three Numbers
- PHP Program - Print Floyd's Triangle