Transforming a String into a number an reverting it PHP
I need to check if a number is palindrome, i started thinking maybe the best way to do it, is transforming the number into a string and verifying the reverse string is the same.
The problem is that when i use the following code i got the wrong result.
<?PHP
function palindrome($number){
$value = strval($number);
开发者_运维知识库 $reverse_value = strrev($value);
if($value == strrev($value)){
echo " $number is a palindrome";
echo gettype($value);
}else{
echo "$number is not a palindrome";
echo $value." ".strrev($value);
}
}
$number = 90209;
palindrome($number);
?>
Can somebody explain me the diference?
It seems that you have deeper problems, because I just put that code into an ide:
https://ideone.com/yJEz1
Result: 90209 is a palindromestring
And it successfully put out the value. You may want to check your php.ini with regard to changed mathematical settings, or just run the code again in a different context, or clean up duplication in the code, and it may give you the right result.
Here is the same code using (string)
casting to ensure the string type (I've never used the strval() function, personally, I just force cast a type). It works in all of three test cases.
https://ideone.com/4bI0O
It works fine, although you're not actually using $reverse_value at all.
if ($value == $reverse_value)
{
...
What does your system say $value and $reverse_value actually are?
Here is an optimized version that works:
function is_palindrome( $value ) {
$reverse_value = strrev( $value );
if ( $value == $reverse_value ) {
echo print_r( $value, true ) . "is a palindrome. The reverse is: " . print_r( $reverse_value, true ) . "<br />";
}
else {
echo print_r( $value, true ) . "is a not a palindrome. The reverse is: " . print_r( $reverse_value, true ) . "<br />";
}
}
There is no need to convert the value to a string; this happens automatically. Also, your code called strrev() twice, so I removed the redundant one.
精彩评论