Home >Backend Development >PHP Tutorial >PHP string flip example code_PHP tutorial
Character flipping is a piece of cake for PHP to process. PHP's string function strrev can handle it. For example:
echo strrev("Hello World!"); //The output result is "!dlroW olleH"
But sometimes during interviews we often need to write a function ourselves to achieve the same effect as strrev. In fact, this is not difficult, for example:
/**
* Function to implement string flipping
* @param string $str The string to be processed
* @return string The successfully flipped string
*/
function reverse($str){
If($str == ''){
return null;
}
If(strlen($str) == 1){
return $str;
}else{
$string = "";
for($i=1;$i<=strlen($str);$i++){
$string .=substr($str,-$i,1);
}
return $string;
}
}
echo reverse("Hello World!"); //The output result is "!dlroW olleH"
Excerpted from: Shine’s Holy Paradise