Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

<?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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
359 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)."
";
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...