topsogus topsogus - 1 month ago 6
PHP Question

Calculate data for loop

I have list, for example:

<ul>
<li>text</li>
<li>text</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li class="add">add</li>
<li class="add">add</li>
</ul>


And next I generate this list in PHP:

<ul>
<?php for ($i=1; $i <= 11; $i++): ?>
<li>text</li>
<?php if (in_array($i, array(3, 4, 10))): ?>
<li class="add">add</li>
<?php endif ?>
<?php if (in_array($i, array(10))): ?>
<li class="add">add</li>
<?php endif ?>
<?php endfor ?>
</ul>


This working good. This is schema and if $i > 11 this should add li.add from beginning. For example:

<ul>
<li>text</li>
<li>text</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li class="add">add</li>
<li class="add">add</li>
//NEXT
<li>text</li>
<li>text</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li class="add">add</li>
<li class="add">add</li>
// NEXT
<li>text</li>
<li>text</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li class="add">add</li>
<li>text</li>
<li>text</li>
//END - NOT 11!
</ul>


So in PHP I must:

<ul>
<?php for ($i=1; $i <= 28; $i++): ?>
<li>text</li>
<?php if (in_array($i, array(3, 4, 10, 14, 15, 21, 25, 26))): ?>
<li class="add">add</li>
<?php endif ?>
<?php if (in_array($i, array(10, 21))): ?>
<li class="add">add</li>
<?php endif ?>
<?php endfor ?>
</ul>


How can I calculate positions for in_arrays automatically? Always after 3, 4 and 10 in one loop (11 items) this should add li.add.

Answer

You don't need to recalculate anything as long as your rule is consisntent:

<ul>
<?php for ($i=1; $i <= 22; $i++): ?>
<li>text</li>
<?php if (in_array($i%11, array(3, 4, 10))): ?>
<li class="add">add</li>
<?php endif ?>
<?php if (in_array($i%11, array(10))): ?>
<li class="add">add</li>
<?php endif ?>
<?php endfor ?>
</ul>

For $i < 11 then ($i%11) = $i then it goes around again.