0

I would like to split an array of strings into 3 parts (in PHP), however I do not know if the number of words will be divible by 3. what would you do in this instance?

let's say i had a larger amount of text than this example example input: 'Here is a sentence of random lenth'

example output: 'Here is', 'a sentence', 'of random length'

timtam
  • 23
  • 4
  • 1
    possible duplicate of [php : exploding string into equal portions. How do i do it!](http://stackoverflow.com/questions/6173250/php-exploding-string-into-equal-portions-how-do-i-do-it) – Yoshi Jun 29 '11 at 06:51

2 Answers2

1
<?php
$a=array("a"=>"apple","b"=>"grapes","c"=>"Horse","d"=>"Cow");
print_r(array_chunk($a,2,true));
?>

output will be

Array (
[0] => Array ( [a] => apple [b] => grapes)
[1] => Array ( [c] => Horse [d] => Cow )
)

I think you can use array_chunk().

HaskellElephant
  • 9,819
  • 4
  • 38
  • 67
jeni
  • 442
  • 1
  • 4
  • 12
0

You can check with the Modulus operand (see http://www.php.net/manual/en/language.operators.arithmetic.php)

$words = explode(' ',$string);
$numberOfWOrds = count($words);
if($numberOfWords % 3 == 0){
    //dividable by three
}else {
    // not dividable by three
}
konsolenfreddy
  • 9,551
  • 1
  • 25
  • 36
  • i guess I can pop the last element until it is divisible by 3 – timtam Jun 29 '11 at 06:47
  • If you don't care about the last elements, you can just `floor($numberOfWords)/3` to get the number of words per output. Then simply iterate by this number over your sentence. – konsolenfreddy Jun 29 '11 at 06:53