Home > Blockchain >  Php check words are the same forward and backwards
Php check words are the same forward and backwards

Time:10-06

I have seen this php function on stack overflow to check if a word is the same forward and backwards but I haven’t found any help on checking multiple words at once. How to code the php so that it would display the code below as Civic is a palindrome Geography is not a palindrome Great full of any help Thanks

<?php
$arr = ('civic','geography');
$word =strtolower($arr);
$reverse=strrev($word); 
if ($word == $reverse) {
    echo "<p style='color:green;'>";
    echo " $word is a palindrome </p>";
} else {
    echo "<p style='color:red;'>";
    echo " $word is not a palindrome </p>";
}
?>

CodePudding user response:

Here is your solution:

$arr = array('civic','geography');
foreach($arr as $word) {
    $word = strtolower($word);
    $reverse = strrev($word); 
    if ($word == $reverse) {
        echo "<p style='color:green;'>";
        echo " $word is a palindrome </p>";
    } else {
        echo "<p style='color:red;'>";
        echo " $word is not a palindrome </p>";
    }
}

I suggest you to read about loops

CodePudding user response:

You can just iterate over every item in the array and echo out what you want.

<?php
$arr = ('civic','geography');
foreach ($arr as &$word) {
    $word =strtolower($word);
    $reverse=strrev($word); 
    if ($word == $reverse) {
        echo "<p style='color:green;'>";
        echo " $word is a palindrome </p>";
    } else {
        echo "<p style='color:red;'>";
        echo " $word is not a palindrome </p>";
    }
}
?>
  • Related