How to get element index in foreach loop in PHP?
Hello everyone! I just started learning PHP and ran into a problem. I have an array with users, and I want to display them as a numbered list. I'm using a foreach loop, but I can't figure out how to get the current iteration number (index).
Here's my code:
```php
$users = ['Anna', 'Boris', 'Viktor', 'Galina'];
foreach ($users as $user) {
echo $user . '
'; } ``` It just outputs the names, but I need it to be: 1. Anna 2. Boris 3. Viktor 4. Galina I know that in a regular for loop you can use a counter variable, but in foreach I don't understand how to do this. I tried adding $i = 0; before the loop and doing $i++ inside, but it seems like a hack. Is there a built-in way to get the element index in foreach? I'm also interested in how to handle associative arrays — there in
'; } ``` It just outputs the names, but I need it to be: 1. Anna 2. Boris 3. Viktor 4. Galina I know that in a regular for loop you can use a counter variable, but in foreach I don't understand how to do this. I tried adding $i = 0; before the loop and doing $i++ inside, but it seems like a hack. Is there a built-in way to get the element index in foreach? I'm also interested in how to handle associative arrays — there in
No answers yet.
Log in to leave an answer