Given:
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
How do I get the current index of $rows during any given iteration, without a separate count variable?
What I tried:
foreach ($rows as $key => $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
EDIT BELOW
But $key gives me the current index of $row, not the current index of $rows.
What I want to do is:
foreach ($rows as $row) {
if(current_index($rows) == 0){
// do something
}
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
To my knowledge, PHP doesn't have a current_index() function or something like it.
Here's what $rows looks like:
Array
(
[0] => Array
(
[id] => 1
[firstname] => Firstname one
[lastname] => Lastname one
)
[1] => Array
(
[id] => 2
[firstname] => Firstname two
[lastname] => Lastname two
)
[2] => Array
(
[id] => 3
[firstname] => Firstname three
[lastname] => Lastname three
)
)
$keyin the loop and are you sure it is not what you want? 2) Please make a little example with an array what you get now as output and what you expected to getBut this gives me the current index of $row, not the current index of $rows.throw new Exception("Unclear question");$keyis the current index of$rows, which you are iterating. ((Otherwise make an example of the current output + expected output with the shown example array))