Auto incrementing number in PHP foreach loop

28,847

Solution 1

<?php 
$n = 0;
foreach ($_productCollection as $_product): 
$n++;
?>
<div style="float: left; font-size: 120px;height:50px;padding-top:50px; color:#ccc"><?php echo $n; ?>
</div>
<div class="listing-item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">

Solution 2

You could use array_keys() to get an indexed array from an associative array, at which point foreach will yield the index as the new key, and the old key as the new value. Indexing the old array with the new value will give you the old value, and the new key will be a counter for elements in the array.

Share:
28,847
a1anm
Author by

a1anm

Updated on July 09, 2022

Comments

  • a1anm
    a1anm almost 2 years

    This is the beginning of a php for loop. I would like to edit it so that 'INSERT NUMBER HERE' gets replaced with an incrementing number. Ie. first loop it would be 1, then 2, then 3 etc.

    <?php foreach ($_productCollection as $_product): ?>
        <div style="float: left; font-size: 120px;height:50px;padding-top:50px; color:#ccc">INSERT NUMBER HERE</div>
        <div class="listing-item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
    

    How can I achieve this?

    Thanks