kiarashi kiarashi - 3 months ago 23
PHP Question

Counting without foreach

While I know how to create a counting inside a foreach,

$i = -1;
foreach ($menu_items as $item => $value) :
...
$i--;
endforeach;


I want to create the same counting effect but my own code isn't inside a foreach. A sample of my code is like this:

<ul>
<li>...</li>
<li class="menu-item[<?php echo esc_attr( $count ); ?>]">...</li>
<li class="menu-item[<?php echo esc_attr( $count ); ?>]">
<ul>
<li class="menu-item[<?php echo esc_attr( $count ); ?>]"></li>
<li class="menu-item[<?php echo esc_attr( $count ); ?>]"></li>
</ul>
</li>
<li class="menu-item[<?php echo esc_attr( $count ); ?>]">...</li>
</ul>


Outcome should be like this.

<ul>
<li>...</li>
<li class="menu-item[-1]">...</li>
<li class="menu-item[-2]">...</li>
<li class="menu-item[-3]">
<ul>
<li class="menu-item[-4]"></li>
<li class="menu-item[-5]"></li>
</ul>
</li>
<li class="menu-item[-6]">...</li>
</ul>


Any help is much appreciated.

Answer

try this..

<ul>
<li>...</li>
<li class="menu-item[<?php $count = -1; echo esc_attr( $count ); ?>]">...</li>
<li class="menu-item[<?php echo esc_attr( --$count ); ?>]">
    <ul>
        <li class="menu-item[<?php echo esc_attr( --$count ); ?>]"></li>
        <li class="menu-item[<?php echo esc_attr( --$count ); ?>]"></li>
    </ul>
</li>
<li class="menu-item[<?php echo esc_attr( --$count ); ?>]">...</li>
</ul>
Comments