Reputation: 361
So as a title says: I have an array
array(0=>"a"1=>"b"2=>"c"3=>"d"4=>"e"5=>"f")
What I want to do is loop through and chunk results and print them like this
ab
cd
ef
OR
abc
def
So far I got this: I chunked array with array_chunk() like this
$chunks = array_chunk($my_array, 3);
So it gives me result like this:
Array(0 => array(0=>"a"1=>"b"2=>"c")1=>array(4=>"d"5=>"e"6=>"f"))
So I loop through
foreach($chunks as $key => $value){
echo $value.'<br>';}
Current output:
a
b
c
d
e
f
Desire output:
abc
def
Any Ideas?
Also I'm on laravel just in case anyone knows a specific approach
Upvotes: 3
Views: 13359
Reputation: 3608
Since this is tagged with laravel
I assume you want a laravel answer too(?).
You can use the chunk function that comes with laravel
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
Upvotes: 10
Reputation: 11642
The chunks you created are array.
You can prints them when using:
$arr= array(0=>"a",1=>"b",2=>"c",3=>"d",4=>"e",5=>"f");
$chunks = array_chunk($arr, 3);
foreach($chunks as $key => $value)
echo implode("",$value). "\n";
Output:
abc
def
Upvotes: 3