Page 1 of 1
Checking if a value is a palindrome, need help please!
Posted: Mon Nov 21, 2011 11:15 am
by mikeashfield
Code: Select all
<?php
if (isset($_POST['palindrome']) && strlen($_POST['palindrome']) > 1) {
//A value has been passed and is longer than 2 characters.
$check=$_POST['palindrome'];
if ($check === strrev($check)) {
//The value passed is a palindrome
echo $check." is a palindrome!";
}
elseif ($check !== strrev($check)) {
//The value passed is not a palindrome
echo $check." is not a palindrome!";
}
}
else {
//An invalid value was passed.
echo "An invalid value was passed, sorry.";
}
?>
Okay, I'm new to PHP and as such have been messing about, trying to learn some of the functions ect and have been getting the outputs I expect, but when I help (try to, anyway!) the code post is for some reason or another, no good. Could anybody tell me if there's anything wrong with the above code, as I get the outputs I expect. I'm still learning, so any criticism is valued. Thanks.
Re: Checking if a value is a palindrome, need help please!
Posted: Mon Nov 21, 2011 11:29 am
by Celauran
A string of length 1 will always be a palindrome.
Re: Checking if a value is a palindrome, need help please!
Posted: Mon Nov 21, 2011 11:32 am
by maxx99
Not much to do wrong here

...but as far as I remember (correct me if im wrong) "strrev" is compatible only with single byte character-sets

it will fail e.g. UTF-8 chars
Re: Checking if a value is a palindrome, need help please!
Posted: Mon Nov 21, 2011 11:34 am
by mikeashfield
That's why I'm not allowing it.

But thanks for the heads up.
Re: Checking if a value is a palindrome, need help please!
Posted: Mon Nov 21, 2011 11:39 am
by mikeashfield
maxx99 wrote:Not much to do wrong here

...but as far as I remember (correct me if im wrong) "strrev" is compatible only with single byte character-sets

it will fail e.g. UTF-8 chars
Believe me, I've been getting it wrong, all of it, apparently.
So what would be the alternative then?
Re: Checking if a value is a palindrome, need help please!
Posted: Mon Nov 21, 2011 12:01 pm
by maxx99
There is a number of problems and solutions related to this function

Check them out in comment section on
http://php.net/manual/en/function.strrev.php
Re: Checking if a value is a palindrome, need help please!
Posted: Mon Nov 21, 2011 12:12 pm
by Benjamin
Don't know if this will work, but figured I would post it anyway:
Code: Select all
if ($n == implode('', array_reverse(str_split($n)))) {
echo 'yes';
} else {
echo 'no';
}
Re: Checking if a value is a palindrome, need help please!
Posted: Mon Nov 21, 2011 12:48 pm
by maxx99
Both will fail for utf8 encoded string e.g.
Code: Select all
$n = utf8_encode("002 €ąż źź żą€ 200");
but will work for
