junkfoodjunkie junkfoodjunkie - 1 year ago 68
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

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

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
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download