'Create a new line whenever an array value reaches more than 10 characters

Here is my code, but it isn't dynamic. What I need is it will automatically create new line if array value is greater than 10.

<?php
$limit = 10;
$newline = explode(" ",$caption);

$count = count($newline); //count number of array values

$nlimit = strlen($newline[0]) + strlen($newline[1]);

if($limit >= $nlimit)
{
    echo $newline[0] . " ",$newline[1];
}
else
{
    echo $newline[0] . " ","<br>". $newline[1];
}
?>


Solution 1:[1]

$caption = "im trying to figure out how to create a new line whenever an array value reaches more than 10 characters";

$lineCharlimit = 10;

$captionWordsArray = explode( " " ,$caption ); 

$line = '';

foreach( $captionWordsArray as $index => $word )
{
    if( strlen( $line .$word ) > $lineCharlimit )
    {
        echo $line ,'<br>';
        $line = $word;
    }
    else
    {
        $line .= ( $line == '' ? '' : ' ' ) .$word;
    }
}
echo $line;

Will output :

im trying
to figure
out how to
create a
new line
whenever an
array value
reaches
more than
10
characters

But for an output like below ( no line is less than 10 characters unless it is the last word ) :

im trying to
figure out how
to create a
new line whenever
an array value
reaches more
than 10 characters

Modify code as below :

$caption = "im trying to figure out how to create a new line whenever an array value reaches more than 10 characters";

$lineCharlimit = 10;

$captionWordsArray = explode( " " ,$caption ); 

$line = '';

foreach( $captionWordsArray as $index => $word )
{
    $line .= ( $line == '' ? '' : ' ' ) .$word;

    if( strlen( $line ) > $lineCharlimit )
    {
        echo $line ,'<br>';
        $line = '';
    }
}
echo $line;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1