Skip to content

Instantly share code, notes, and snippets.

@nadeem-khan
Last active May 3, 2017 17:41
Show Gist options
  • Save nadeem-khan/89fbc8fe499b38d7e394659b8d4215cc to your computer and use it in GitHub Desktop.
Save nadeem-khan/89fbc8fe499b38d7e394659b8d4215cc to your computer and use it in GitHub Desktop.
Detect a palindrome.md

Detect a Palindrome



/**
 * A palindrome is a word which reads the same backward or forward, 
 * such as madam or kayak
 *
 * Implement a function that returns true if a word is a palindrome 
 * and false otherwise
 *
 * Do not worry about edge cases. You can assume that the input will
 * always be alphanumeric characters [A-Za-z]
 */
function is_palindrome($string) {
    $string = strtolower($string);
    $reverse = '';
    $i = 0;
    while (!empty($string[$i])) {
        $reverse = $string[$i] . $reverse;
        $i++;
    }
    $match = 0;
    for ($z = 0; $z < strlen($reverse); $z++) {
        if ($reverse[$z] == $string[$z]) {
            $match++;
        }
    }


    if ($match == strlen($string)) {
        return true;
    } else {
        return false;
    }
}

var_dump(is_palindrome('a') === true);
var_dump(is_palindrome('madam') === true);
var_dump(is_palindrome('Kayak') === true);
var_dump(is_palindrome('foobar') === false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment