I am learning php and wanted to try out recursion. I have made a function which gets a word and if its' length is over 30 characters it divides it into halves. And I have made a recursion, so if one of a halves is over 30 words, it divides it as well and so on.
function breakLongWords($val) {
$array = explode(" ", $val);
foreach ($array as $key => $word) {
if (strlen($word) > 30) {
for ($i = strlen($word) + 1; $i >= round(strlen($word)/2); $i--) {
$word[$i+1] = $word[$i];
if ($i == round(strlen($word)/2)) {
$word[$i] = " ";
}
}
breakLongWords($word);
$array[$key] = $word;
}
$result = implode(" ", $array);
}
var_dump($result);
}
$str = "SuperDuperExtraGiggaDoubleTrippleSpicyWithCheeseLongUnlimitedString123";
breakLongWords($str);
I am testing it out in repl.it with var_dump function. Somehow last result is an entry word divided into two halves instead of four (70 characters). However one of the "var_dumps" prints correct result.
string(37) "SuperDuperExtraGigg aDoubleTrippleSpi"
string(35) "cyWithCheeseLongUn limitedString123"
string(73) "SuperDuperExtraGigg aDoubleTrippleSpi cyWithCheeseLongUn limitedString123"
string(71) "SuperDuperExtraGiggaDoubleTrippleSpi cyWithCheeseLongUnlimitedString123"
Could you help me please solve this issue?