1

I use the following code to output content of an array:

$txt = sprintf("%s %s %s %s %s %s %s", $myarray[1], $myarray[2], $myarray[3], $myarray[4], $myarray[5], $myarray[6], $myarray[7]);
echo $txt; 

echo "<br />";

$txt = sprintf("%s %s %s %s %s %s %s", $myarray[8], $myarray[9], $myarray[10], $myarray[11], $myarray[12], $myarray[13], $myarray[14]);
echo $txt; 

echo "<br />";

$txt = sprintf("%s %s %s %s %s %s %s", $myarray[15], $myarray[16], $myarray[17], $myarray[18], $myarray[19], $myarray[20], $myarray[21]);
echo $txt; here

Now I want to loop it, I tried something like this:

for($a=1, $b=2, $c=3, $d=4, $e=5, $f=6, $g=7; $i<=count($myarray); $a,$b,$c,$d,$e,$f,$g +=7)
{

    $txt = sprintf("%s %s %s %s %s %s %s", $myarray[$a], $myarray[$b], $myarray[$c], $myarray[$d], $myarray[$e], $myarray[$f], $myarray[$g]);
    echo $txt; 

}

but unfortunately it does not work.

3
  • What is your input and expected output. Please elaborate it more..unclear Commented Sep 28, 2015 at 11:22
  • Google: PHP array_chunk() + PHP implode() Commented Sep 28, 2015 at 11:23
  • Change the increment variables to $a+=7,$b+=7,$c+=7,$d+=7,$e+=7,$f+=7,$g +=7 Commented Sep 28, 2015 at 11:30

3 Answers 3

2

My approach would be:

  • Increment $i by 7 on every iteration.
  • Use array_slice to get 7 items with offset of $i.
  • Use vsprintf what takes arguments as array.

Try this:

for ($i=0; $i < count($myArray); $i+=7) {
    echo vsprintf("%s %s %s %s %s %s %s", array_slice($myArray, $i, 7)).'<br />';
}

or use implode, so code looks cleaner.

for ($i=0; $i < count($myArray); $i+=7) {
    echo implode(" ", array_slice($myArray, $i, 7)).'<br />';
}
1
$size = 6;

foreach(array_chunk($array, $size) as $values) {
    echo implode(' ', $values) . '<br />';
}
0

You didn't initialize and increment $i, i think that may cause the problem.

Please try this,

for($a=1, $b=2, $c=3, $d=4, $e=5, $f=6, $g=7,$i=1; $i<=3; $a+=7,$b+=7,$c+=7,$d+=7,$e+=7,$f+=7,$g+=7,$i++)
{
$txt = sprintf("%s %s %s %s %s %s %s", $myarray[$a], $myarray[$b], $myarray[$c], $myarray[$d], $myarray[$e], $myarray[$f], $myarray[$g]);
echo $txt; 
}

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.