我如何使用python'就像"For循环"在PHP中反转字符串


how can i use python's like "For loop" in php to reverse string?

python代码:

def is_palindrome(s):
    return revers(s) == s
def revers(s):
    ret = ''
    for ch in s:
        ret = ch + ret
    return ret
print is_palindrome('RACECAR') 
# that will print true

当我将函数转换为php时

function is_palindrome($string){
    if (strrev($string) == $string) return true;
    return false;
}
$word = "RACECAR";
var_dump(is_palindrome($word));
// true 

两个函数都工作得很好,但是,我怎么能在循环中与php反转字符串??

$string = str_split(hello);
$output = '';
foreach($string as $c){
        $output .= $c;
}
print $output;
// output 
hello 
//i did this,

这是工作发现,但有没有更好的方法?$string = "hello";$len ($string);

$ret = '';
for($i = $lent; ($i > 0) or ($i == 0); $i--)
{
    $ret .= $string[$i];
    #$lent = $lent - 1;
}
print $output;
//output 
olleh

Replace

$output .= $c;

$output = $c . $output;

我猜不能更短了。使用循环:)

$word = "Hello";
$result = '';
foreach($word as $letter)
    $result = $letter . $result;
echo $result;

我没有尝试这段代码,但我认为它应该工作:

$string = "hello";
$output = "";
$arr = array_reverse(str_split($string)); // Transform "" to [] and then reverse => ["o","l","l,"e","h"]
foreach($arr as $char) {
    $output .= $char;
}
echo $output;

的另一种方法:

$string = "hello";
$output = "";
for($i = strlen($string); $i >= 0; $i--) {
    $output .= substr($string, $i, 1);
}
echo $output;

strrev()是PHP中用于反转字符串的函数。http://php.net/manual/en/function.strrev.php

$s = "foobar";
echo strrev($s); //raboof

如果你想检查一个单词是否是回文:

function is_palindrome($word){ return strrev($word) == $word }
$s = "RACECAR";
echo $s." is ".((is_palindrome($s))?"":"NOT ")."a palindrome";