PHP function Exercises: Checks whether a passed string is a palindrome or not
PHP function: Exercise-6 with Solution
Write a PHP function that checks whether a passed string is a palindrome or not?
A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
Pictorial Presentation:
Sample Solution:
PHP Code:
<?php
// Define a function to check if a string is a palindrome
function check_palindrome($string)
{
// Check if the reversed string is equal to the original string
if ($string == strrev($string))
return 1; // Return 1 if it is a palindrome
else
return 0; // Return 0 if it is not a palindrome
}
// Test the function with the string 'madam' and display the result
echo check_palindrome('madam')."\n"; // Output: 1 (true) since 'madam' is a palindrome
?>
Output:
1
Explanation:
In the exercise above,
- The function "check_palindrome()" takes a string '$string' as input.
- Inside the function, it uses the "strrev()" function to reverse the input string.
- It then compares the reversed string with the original string using the equality operator (==).
- If the reversed string is equal to the original string, it returns 1, indicating that the string is a palindrome.
- If the reversed string is not equal to the original string, it returns 0, indicating that the string is not a palindrome.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP function that checks if a string is all lower case.
Next: PHP Regular Expression Exercises Home
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/php-function-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics