0

Sorry, but it might be a very simple answer.

I do have an array:

Array ( [0] => 3 [1] => 0 )

If I do this:

foreach($array as $key){
    $index = $key;
    print_r($index);
}

Of course I get:

3

0

I want to have a variable with the index:

0

1

How do I do it? It should be very simple. I am disparing! Thanks for help!

3 Answers 3

1
foreach ($array as $key => $value) {
  ...
}

or

foreach(array_keys($array) as $key) {
   $value = $array[$key];
}
Sign up to request clarification or add additional context in comments.

6 Comments

In your first suggestion. What do I have to type to get the index-position?
$key will be the array index that's currently being evaluated (your 0, 1, etc...). Either version gives you the same value.
No $key is returning 3 and 0. Not the index 0 & 1. I want the postion of 3 and 0, so I want 0 & 1 in the foreach-loop. Do you know what I mean?
Yes, and what I've suggested would work. The $key => $val construct gets you both the array's keys (0,1,...) and the values (3,0,...). If you've got non-consecutive keys, then you'll have to count the position yourself.
Yes, but how do I get the index? If I do foreach($array as $key=>$val){print_r($key);} I get 3 and 0, not the index 0 and 1. But I need this loop foreach($array as $key=>$val). How do I count the position? Thanks a lot!
|
0
foreach ($array as $key => $val) {
  print $key;
}

...or use array_keys()

Comments

0

There are two versions of the foreach() statement, the following returns the array keys and values.

foreach($array as $key => $value){
    echo $key.' => '.$value;  // Outputs 0 => 3, 1 => 0
}

$key is the array key (or index) ie. 0 and 1. $value is the value for the corresponding array $key ie. 3 and 0.

The other format of the foreach() statement is what you have in your question and returns just the array values (although you call this $key in your code), so...

foreach($array as $value){
    echo $value;  // Outputs 3, 0
}

Comments

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.