2

Is there a way in PHP to select multiple array elements at once, e.g. such that in a for loop, $i = size of first set to be selected, and then subsequent increments represent selecting the next set of that size, from an array - ?

Thanks!

2
  • I.e. instead of just looping through one array element at a time, but to loop through selected pairs instead (e.g. 3 elements, and then to do something to those 3). Commented Feb 26, 2012 at 12:33
  • Have you looked into the php array_slice function? is this what you're looking for? for ($i=0;$i<$x;$i+=$range) {$slice=array_slice($arr,$i, $range);print_r($slice);} Commented Feb 26, 2012 at 12:41

3 Answers 3

2

I.e. instead of just looping through one array element at a time, but to loop through selected pairs instead (e.g. 3 elements, and then to do something to those 3).

there are many ways to do it.
one would be

$arr = array(1,2,3,4,5,6,7,8,9);
$new = array_chunk($arr,3);
foreach ($new as $chunk) {
  print_r($chunk);// 3 elements to do something with
}
Sign up to request clarification or add additional context in comments.

Comments

2

It depends on how you want to group your elements.

$i = 4;
$source = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 );
// If you want consecutive elements in the same group, i.e. the first $i elements etc
$chunks = array_chunk( $source, $i );
foreach( $chunks as $chunk )
{
    // Iterate over chunk
    echo '---<br />';
    foreach( $chunk as $element )
    {
        echo $element . '<br />';
    }
}
echo '---<br />';
echo '---<br />';
// Otherwise if you want consecutive elements in separate groups
$lastElement = count( $source ) - 1;
$step = ceil( count( $source) / $i );
for( $offset = 0; $offset < $step; $offset++ )
{
    echo '---<br />';
    for( $element = $offset; $element <= $lastElement; $element+= $step )
    {
        echo $source[$element] . '<br />';
    }
}
echo '---<br />';

Comments

1

If I understand your question right you have something like this?

$array = array( "A" => array("a","b"),
                "B" => array("a","b"),
                "C" => array("a","b"));

and you want to loop thought A, B, C at the same same time?

Then you can do something like this;

for($i=0;$i<=max(count($array['A']),count($array['B']),count($array['B']))){
     if(count($array['A'])<=$i+1) {
         echo $array['A'][$i];
     }
     if(count($array['B'])<=$i+1) {
         echo $array['B'][$i];
     }
     if(count($array['B'])<=$i+1) {
         echo $array['B'][$i];
     }
     $i++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.