How can I get the current element number when I\'m traversing a array?
I know about count(), but I was hoping there\'s a built-in function for getting the current field
PHP arrays are both integer-indexed and string-indexed. You can even mix them:
array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');
What do you want the index to be for the value 'blue'
? Is it 3? But that's actually the index of the value 'yellow'
, so that would be an ambiguity.
Another solution for you is to coerce the array to an integer-indexed list of values.
foreach (array_values($array) as $i => $value) {
echo "$i: $value\n";
}
Output:
0: red
1: green
2: white
3: blue
4: yellow
function Index($index) {
$Count = count($YOUR_ARRAY);
if ($index <= $Count) {
$Keys = array_keys($YOUR_ARRAY);
$Value = array_values($YOUR_ARRAY);
return $Keys[$index] . ' = ' . $Value[$index];
} else {
return "Out of the ring";
}
}
echo 'Index : ' . Index(0);
Replace the ( $YOUR_ARRAY )
You should use the key() function.
key($array)
should return the current key.
If you need the position of the current key:
array_search($key, array_keys($array));
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
foreach() {
$i++;
if(index($key) == $i){}
//
}
I recently had to figure this out for myself and ended up on a solution inspired by @Zahymaka 's answer, but solving the 2x looping of the array.
What you can do is create an array with all your keys, in the order they exist, and then loop through that.
$keys=array_keys($items);
foreach($keys as $index=>$key){
echo "position: $index".PHP_EOL."item: ".PHP_EOL;
var_dump($items[$key]);
...
}
PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else