I have a function to split a string into 2 equal parts based on the number of words in the string. I am then wrapping the 2 new strings in individual span
s. In the event that there’s an odd number of words in the original string, I would like the 2nd span to contain the 1 additional word.
Currently the additional word is going to the first span
:
$array = explode( ' ', 'Lorem ipsum dolor sit amet' );
$count = count( $array );
$per_part = max( round( $count / 2 ), 1 );
$new_array = [];
for ( $i = 0; $i < 2; $i++ ) {
$new_array[] = array_slice( $array, $i * $per_part, $per_part );
}
$first_string = join(' ', $new_array[0]);
$second_string = join(' ', $new_array[1]);
$new_string = '<span>' . $first_string . '</span>' . ' <span>' . $second_string . '</span>';
echo htmlspecialchars($new_string);
Current result:
<span>Lorem ipsum dolor</span> <span>sit amet</span>
Desired result:
<span>Lorem ipsum</span> <span>dolor sit amet</span>
3
Answers
You can try by calculating how many words each part should contain based on whether the total word count is even or odd, so if it’s even, both parts will contain the same number of words, and if it’s odd, the first part will contain one additional word. Something like this
I think you can use
ceil()
to round up the result, that way the extra word will go to the second span if the result number of words is odd:Calculate the number of words per part by rounding down the total count of words divided by 2. This will give you the number of words for the first part. Then, calculate the remaining words which will be added to the second part.
floor( $count / 2 )
is used to ensures that the first part gets the majority of the words when the total count is odd. The remaining words are then added to the second part. This way, if there’s an odd number of words in the original string, the 2nd span will contain the 1 additional word.