Reputation: 830
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!
Upvotes: 0
Views: 2817
Reputation: 45829
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
}
Upvotes: 0
Reputation: 88677
foreach ($array as $key => $val) {
print $key;
}
...or use array_keys()
Upvotes: 0
Reputation: 360732
foreach ($array as $key => $value) {
...
}
or
foreach(array_keys($array) as $key) {
$value = $array[$key];
}
Upvotes: 1