a1anm
a1anm

Reputation: 1629

Auto incrementing number in PHP foreach loop

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

Upvotes: 3

Views: 30863

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

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.

Upvotes: 3

dfilkovi
dfilkovi

Reputation: 3081

<?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; ?>">

Upvotes: 13

Related Questions