Palindrome Checking with PHP
-
@scottalanmiller created two threads involving Python and palindromes:
http://mangolassi.it/topic/3472/palandrome-checking-with-python
http://mangolassi.it/topic/3471/recursive-palandrome-checking-in-pythonI thought I'd be a smarty pants and do the same thing in PHP, also without a loop:
<?php echo 'Your palindrome is: '; $pal = trim(fgets(STDIN)); if ($pal == strrev($pal)) { echo 'It\'s good.'; } else { echo 'Fail'; }
Just remember: in interpreted languages, native functions/methods are always faster, don't reinvent the wheel and make it into a triangle.
However, typically the point of questions like this may be to test if the developer knows how to do recursion without using classic loops (for, while, do, foreach, whatever), and the secret sauce here is simply calling a function from itself:
<?php itsaloop(); function itsaloop($i = 0) { echo $i . "\n"; // One could also use global $i instead of passing the variable as a parameter or get even more fancy and pass by reference. if ($i < 10) { itsaloop($i); $i++; } }
I use this as one of three primary test questions for hiring programmers, almost everyone fails this one, and it's the first one -- and they can be completed in any Turing complete language. Some even claim that it's impossible. Understanding a language, how it works, and being able to think of things in a simple manner is important to being a good programmer, and unfortunately most programmers aren't any good. Being able to pass questions like this, in any language, really shows that one could learn essentially any programming language.
-
Hey awesome, great idea. Now go make a Lua one!