php foreach as key, every two number as a group
Asked Answered
L

3

5
<?php
$data=array('1','2','3','4','5','6','7','8','9','10','11');
foreach($data as $key=> $element){
    if($key % 2 != 0){
        echo $element.'<br />';
    }
    echo '<hr />';
}
?>

php foreach as key, how to make every two number as a group?

I want to output:

1,2
_____
3,4
_____
5,6
_____
7,8
_____
9,10
_____
11
Lamonicalamont answered 27/7, 2011 at 23:42 Comment(0)
T
23

Have a look at the array_chunk() function.

In your case you'd use it like this:

foreach(array_chunk($data, 2) as $values) {
    echo implode(',', $values)."\n";
}

During the last iteration $values will have only one element so if you plan to access the elements directly using their index remember to use count() to check the array's element count.

Teddman answered 27/7, 2011 at 23:45 Comment(0)
T
7

Your foreach() is fine but you want to print every element, not just every even one. You also don't want the horizontal rule every time either, just every even. Thus:

<?php
$data=array('1','2','3','4','5','6','7','8','9','10','11');
foreach($data as $key=> $element){
    echo $element;
    if($key % 2 != 0){
        echo "<br/><hr />";
    }
    else {
        echo ",";
    }
}
?>
Trustbuster answered 27/7, 2011 at 23:49 Comment(0)
S
0

Here's a functional-style script. array_chunk() with produce sets of elements with a count no larger than the nominated size. implode() will only insert the delimiting string if it is necessary.

Code: (Demo)

$data = range(1, 11);

echo implode(
    "\n",
    array_map(
        fn($chunk) => implode(', ', $chunk),
        array_chunk($data, 2)
    )
);

Output:

1, 2
3, 4
5, 6
7, 8
9, 10
11
Soapwort answered 22/5 at 9:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.