Problem with simple palindrome program

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
utsavgupta
Forum Newbie
Posts: 3
Joined: Thu Apr 03, 2008 1:51 am
Location: India

Problem with simple palindrome program

Post by utsavgupta »

Hi,

First let me tell you guys, this is my first post and I'm new to Php coding.

I have written the palindrome program in various programming languages with the same logic. They work perfectly on all but in php it's not working. The code is given below, please tell me where am I making the mistake.

Code: Select all

 
<html>
<head>
<title>Palindrome Checker</title>
</head>
<body>
<?php
    $a=$_GET['num'];
    $b=$a;
    $x=0;
    while($a > 0)
    {
        $x=$x*10;
        $x=$x + ($a % 10);
        $a=$a / 10;
    }
    if($x==$b)
    {
        echo ("Given number is a palindrome!");
    }
    else
    {
        echo ("Given number is not a palindrome!");
    }
?>
</body>
</html>
 

Thanks in advance.

Cheers,
Utsav Gupta
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Problem with simple palindrome program

Post by onion2k »

Shouldn't "while($a > 0)" be "while($a > 1)"?

EDIT: Personally, I'd do..

Code: Select all

if (strrev(strval($_GET['num'])) == strval($_GET['num'])) { echo "It's a palindrome."; }
Much easier. And it'd work for words.
utsavgupta
Forum Newbie
Posts: 3
Joined: Thu Apr 03, 2008 1:51 am
Location: India

Re: Problem with simple palindrome program

Post by utsavgupta »

Thanks now it's working fine
Post Reply