3v4l.org

run code in 300+ PHP versions simultaneously
<?php $longString = 'I like apple. You like oranges. We like fruit. I like meat, also.'; $maxLineLength = 18; $words = explode(' ', $longString); $currentLength = 0; $index = 0; foreach ($words as $word) { // +1 because the word will receive back the space in the end that it loses in explode() $wordLength = strlen($word) + 1; if (($currentLength + $wordLength) <= $maxLineLength) { $output[$index] .= $word . ' '; $currentLength += $wordLength; } else { $index += 1; $currentLength = $wordLength; $output[$index] = $word; } } var_export($output);
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
Warning: Undefined variable $output in /in/Ref5f on line 16 Warning: Undefined array key 0 in /in/Ref5f on line 16 array ( 0 => 'I like apple. You ', 1 => 'likeoranges. We ', 2 => 'likefruit. I ', 3 => 'likemeat, also. ', )
Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33
Notice: Undefined variable: output in /in/Ref5f on line 16 Notice: Undefined offset: 0 in /in/Ref5f on line 16 array ( 0 => 'I like apple. You ', 1 => 'likeoranges. We ', 2 => 'likefruit. I ', 3 => 'likemeat, also. ', )

preferences:
140.73 ms | 408 KiB | 5 Q