How to use foreach loop with index in PHP?
In PHP, the foreach
loop with the key => value
format is used to iterate over associative or indexed arrays. This format allows us to access both the key (or index) and the value of each element during the loop.
Syntax:
foreach ($array as $key => $value) {
// Code to execute using $key and $value
}
$array
– The array we want to loop through.$key
– The index or key of the current element.$value
– The value of the current element.
How It Works:
1. PHP extracts each key-value pair from the array.
2.On each iteration:
- The key is assigned to the
$key
variable. - The value is assigned to the
$value
variable.
3.The loop continues until all elements have been processed.
Example:
$users = ['kohli', 'smith', 'maxwell'];
foreach( $users as $index => $value ){
echo "Index: $index, Value: $value\n";
}
Output:
