Tuesday, June 4, 2013

Palindrome number or string

Question: We have to ask user to enter number or string he/she wants, and give output is number/string Palindrome or not?
(abcba-Palindrome String)
(abccba-Palindrome String)
(12321-Palindrome Number)
(123321-Palindrome Number)

Answer: Copy the below code and paste it into "your.php" file. After done this you will just need to run "your.php" file in browser and you will get the output successfully.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Palindrome number or string</title>
    </head>

    <body>
        <h1><center>Palindrome number or string</center></h1>

        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            Enter number or string:<input type="text" name="num"/>
            <input type="submit" name="submit" value="OK" />
        </form>
        <?php
        if (isset($_POST['submit'])) {
            $num = $_POST['num'];
            $numeric = is_numeric($num);

            function is_palindrome(&$str) {
                for ($i = 0; $i < strlen($str) / 2; $i++) {
                    if ($str[$i] != $str[strlen($str) - 1 - $i])
                        return false;
                }
                return true;
            }

            if (!$numeric) {
                $result = is_palindrome($num);
                if ($result) {
                    echo $num . " is palindrome string";
                }
                else
                    echo $num . " is not palindrome string";
            } else {
                $sum = 0;
                $temp = $num;
                while ($temp >= 1) {
                    $r = $temp % 10;
                    $temp = $temp / 10;
                    $sum = $sum * 10 + $r;
                }

                if ($sum == $num) {
                    echo $num . " is palindrome number";
                }
                else
                    echo $num . " is not palindrome number";
            }
        }
        ?>
    </body>
</html>

No comments:

Post a Comment