views:

55

answers:

4

Is there a better way in PHP to access this array in groups of three?

Let's say my array is a comma separated string like :

("Thora","Birch","Herself","Franklin Delano","Roosevelt","Himself (archive footage)","Martin Luther","King","Himself (archive footage) (uncredited)")

although the array can end up being much larger, each one will be different but still in logical groups of three (firstname, lastname, role).

What I'm trying to accomplish is looping through the array in groups of three, so that the first record would have firstname[0]=>"Thora", lastname[0]=>"Birch" and role[0]=>"Herself".

I'm only used to foreach loops but don't see an extra parameter like "for each 3" so maybe someone can shed some light?

Thanks!

+2  A: 

You can use a for-loop for this, assuming your 'people' array has a length of 3n.

$people = array("Thora","Birch","Herself","Franklin Delano","Roosevelt","Himself (archive footage)","Martin Luther","King","Himself (archive footage) (uncredited)");
$firstName = array();
$lastName = array();
$role = array();
for($i=0; $i<count($people); $i += 3){
   $firstName[] = $people[$i];
   $lastName[] = $people[$i+1];
   $role[] = $people[$i+2];
}
Lekensteyn
+1  A: 

How about Pseudo code

for Index = 0 index = length index +=3
{
   Firstname= array[index]
   middlename = array[index+1]
   lastname = array[index+2]
   Do Something with them...
}
Roadie57
I'm not a PHP programmer, but I can't imagine this not doing EXACTLY what was asked.
Babak Naffas
+4  A: 

PHP has a function called array_chunk designed for this task.

Try this:

$sets = array_chunk($people, 3);
foreach ($sets as $set) {
  //you could use the following line to put each field into a nice variable
  list ($firstname, $lastName, $role) = $set;

  //if all you want to do is collect the values, do this 
  $firstNames[] = $set[0];
  $lastNames[] = $set[1];
  $role[] = $set[2];
}

Note that the last chunk might not be of size 3, so you should check that keys 1 and 2 are set with isset, if you can't guarantee that your array is always a multiple of 3 in length.

David Caunt
make sure to call array_chunk with the chunk size: array_chunk($people, 3)
Mike Axiak
Oops - thanks!!
David Caunt
This is one I haven't heard of, thanks for the help! I'm going to give this a run through tomorrow, looks nice and elegant!
Chris
It's worth having a look through the PHP manual at different array functions, especially when you're about to reinvent the wheel in your own code! Chances are there's a built in function.
David Caunt
Thanks David, this one worked like a charm for what I was doing, and the list function helped out even further.
Chris
+1  A: 

Alternatively, if you use PHP >= 5.3:

array_walk(
        range(1,9),//<== normally your array, range(1,9) is just an example/test value
        function($value,$key) use (&$return){
                 $return[$key % 3][] = $value;
        });
var_dump($return);
Wrikken