junkfoodjunkie junkfoodjunkie - 11 days ago 6
PHP Question

Iterate through PHP array, but output slightly different depending on where in array you currently are

I have an array where I want to iterate through the array, and output the content. So far so good, no problem.
However, I want to output this array into a list (HTML), but only output a new

<li>
for every 5 items in the array. So the result I want is this:

<li><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span></li>
and so forth until the array is done.

I'm probably overthinking this, but currently I have this, which doesn't work properly (I was thinking using modulo to output the
<li></li>
when needed, but... no.

$filetypes = allowedMimeAndExtensions('extension','mime');
for ($c = 0; $c < count($filetypes); $c++) {
if ($c == 0 || $c % 5 == 0) {
echo '<li>';
}
list ($key, $value) = each($filetypes);
echo '<span class="helper" title="'.$value.'">'.$key.'</span>';
if (($c == 5) || ($c % 5 == 0)) {
echo '</li>';
}
}


Anyone able to give me a hint or point me in the right direction here?

Answer

Please read about array_chunk PHP function

It splits long array to multimensional array that contains chunks of input. Eg.

$input = range(1, 10); // [1,2,3,4,5,6,7,8,9,10]
$chunked = array_chunk($input, 4); // [[1,2,3,4].[5,6,7,8],[9,10]];

then use nested foreach to display spans in your li's

Comments