「PHP入門」文字列を反転する方法まとめ

$str = “study it in this site”;
方法1
print_r(strrev($str));

方法2
$newArrFirst = [];
$newStrFirst = ”;
$newArrFirst = str_split($str);
$arrCount = count($newArrFirst);
for ($i=0; $i < $arrCount; $i++) {
$newStrFirst.=$newArrFirst[$i];
}
echo “<pre>”;
print_r($newStrFirst);
echo “</pre>”;

方法3
$newStrSecond = ”;
$arrCountSecond = strlen($str);
for ($i=1; $i <= $arrCountSecond; $i++) {
$newStrSecond.=substr($str, -$i, 1);
}
echo “<pre>”;
print_r($newStrSecond).”\n”;
echo “</pre>”;

方法4
$newStrThird = ”;
$arrCountThird = strlen($str);
for ($i = $arrCountThird; $i>=0;$i–) {
@$newStrThird.=$str[$i];
}
echo “<pre>”;
print_r($newStrThird).”\n”;
echo “</pre>”;

Comments are closed.