How to get the iteration number when scanning an object in php with a foreach loop or an array, where the key is not a number, but a name, but you need to get its position or iteration number?

enter image description here

  • Enter a variable before the loop and increment it in a loop. - Asidert
  • But is there any function for this in php? - Enrico Takatti

2 answers 2

This is just start a variable with a counter:

<?php $counter = 0; $person = array( "first_name" => "Kevin", "last_name" => "Skoglund", "address" => "123 main street", "city" => "Baverly Hils", "state" => "CA", "zip_code" => "90210" ); foreach ($person as $value) { $counter++; // тут твой код } 

The $counter variable is always the iteration number now.

  • and for each array before the cycle it is necessary to invent a new variable name, or can I use this one? - Enrico Takatti
  • this one $ counter - Enrico Takatti
  • Well, it turns out to reset it before each start of the cycle. - Alexandr Gulevskih pm

If without a cycle:

 $person = [ "first_name" => "Kevin", "last_name" => "Skoglund", "address" => "123 main street", "city" => "Baverly Hils", "state" => "CA", "zip_code" => "90210" ]; $idx = array_search("zip_code", array_keys($person)); // $idx = 5