12

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++;
    }
1
  • What use is a numeric index for an associative array? Commented Nov 1, 2011 at 13:09

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

lol thank you @hijarian. It as asked 5 years ago. Now I have written books on PHP
@MarthaJames bwahaha, necroposting! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.