How to get array index in foreach

I have a foreach loop in php to iterate an associative array. Inside the loop, instead of increasing the variable, I want to get the numerical index of the current element. Is it possible.

$arr = array('name'=>'My name','creditcard'=>'234343435355','ssn'=>1450);
foreach($arr as $person){
  // want index here
}

I usually do this to get the index:

$arr = array('name'=>'My name','creditcard'=>'234343435355','ssn'=>1450);
    $counter =0;
    foreach($arr as $person){
      // do a stuff
$counter++;
    }
+5
source share
2 answers

Use this syntax to foreachaccess the key (how $index) and value (how $person)

foreach ($arr as $index => $person) {
   echo "$index = $person";
}

This is explained in the PHP documentation foreach.

+18
source

Why do you need a numeric index inside an associative array? An associative array maps arbitrary values ​​to arbitrary values, as in your example, strings for strings and numbers:

$assoc = [
    'name'=>'My name',
    'creditcard'=>'234343435355',
    'ssn'=>1450
];

. , , :

$numb = [
    0=>'My name',
    1=>'234343435355',
    2=>1450
];

PHP , . , foreach, , , @MichaelBerkowski :

foreach ($arr as $index => $value) 

, $index . -, .

, ?! !

, , , , array_values :

foreach (array_values($assoc) as $value) // etc

, , :

$counter = 0;
foreach ($assoc as $key => $value)
{
    // do stuff with $key and $value
    ++$counter;
}

- array_reduce, .

+2

All Articles