PHP: Check if a String is a Palindrome

Problem Statement:

Write a PHP function that checks if a given string is a palindrome.

Solution Explanation:

  1. Convert the string to lowercase using strtolower().
  2. Remove spaces using str_replace(" ", "", $str).
  3. Reverse the string using strrev().
  4. Compare the original and reversed strings.

PHP Code:

<?php
function isPalindrome($str) {
    $str = strtolower(str_replace(" ", "", $str)); // Convert to lowercase and remove spaces
    return $str === strrev($str); // Compare original with reversed
}

// Test cases
echo isPalindrome("madam") ? "True\n" : "False\n";  // Output: True
echo isPalindrome("racecar") ? "True\n" : "False\n";  // Output: True
echo isPalindrome("hello") ? "True\n" : "False\n";  // Output: False
echo isPalindrome("A man a plan a canal Panama") ? "True\n" : "False\n";  // Output: True
?>


Example Output:

Input: “madam” → Output: True
Input: “hello” → Output: False
Input: “A man a plan a canal Panama” → Output: True

Leave a Reply