简体   繁体   中英

How to get Array index in foreach

I have a foreach loop in php to iterate an associative array. Within the loop, instead of increamenting a variable I want to get numeric index of 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 index:

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

Use this syntax to foreach to access the key (as $index ) and the value (as $person )

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

This is explained in the PHP foreach documentation.

Why would you need a numeric index inside associative array? Associative array maps arbitrary values to arbitrary values, like in your example, strings to strings and numbers:

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

Numeric arrays map consecutive numbers to arbitrary values. In your example if we remove all string keys, numbering will be like this:

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

In PHP you don't have to specify keys in this case, it generates them itself. Now, to get keys in foreach statement, you use the following form, like @MichaelBerkowski already shown you:

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

If you iterate over numbered array, $index will have number values. If you iterate over assoc array, it'll have values of keys you specified.

Seriously, why I am even describing all that?! It's common knowledge straight from the manual!

Now, if you have an associative array with some arbitrary keys and you must know numbered position of the values and you don't care about keys, you can iterate over result of array_values on your array:

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

But if you do care about keys, you have to use additional counter, like you shown yourself:

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

Or some screwed functional-style stuff with array_reduce , doesn't matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM