function formatLines(array $words, int $maxWidth): array {
$result = [];
$currentLine = "";
$currentLength = 0;
foreach ($words as $word) {
$wordLen = strlen($word);
// If adding this word exceeds maxWidth, push current line
if ($currentLength + ($currentLine === "" ? 0 : 1) + $wordLen > $maxWidth) {
if ($currentLine !== "") {
$result[] = $currentLine;
}
$currentLine = $word;
$currentLength = $wordLen;
} else {
if ($currentLine !== "") {
$currentLine .= " ";
$currentLength++;
}
$currentLine .= $word;
$currentLength += $wordLen;
}
}
// Push the last line if not empty
if ($currentLine !== "") {
$result[] = $currentLine;
}
return $result;
}
function main() {
$words = ["This", "is", "a", "programming", "example", "of", "text", "wrapping"];
$maxWidth = 12;
$lines = formatLines($words, $maxWidth);
foreach ($lines as $line) {
echo "\"$line\"\n";
}
}
main();
/*
run:
"This is a"
"programming"
"example of"
"text"
"wrapping"
*/