Home >Backend Development >PHP Tutorial >How to Get Array Keys in a PHP Foreach Loop Correctly?
Getting Array Keys in PHP Foreach Loop
When iterating over an array in PHP using a foreach loop, it is common to want to access the key associated with each element. The original question encountered an issue where the key() function was being used improperly, resulting in incorrect key values. This article provides a solution to this issue and demonstrates how to obtain the desired key values within a foreach loop.
The key to getting the array keys correctly lies in the syntax of the foreach loop. By using the following format:
<code class="php">foreach ($array as $key => $value) { // Access the key and value here }</code>
it is possible to assign both the key and the value to separate variables. In this case, the $key variable will contain the array key associated with the current iteration.
Applying this to the original question, here is the corrected code:
<code class="php">foreach ($samplearr as $key => $item) { print "<tr><td>" . $key . "</td><td>" . $item['value1'] . "</td><td>" . $item['value2'] . "</td></tr>"; }</code>
By using the $key variable to access the array key, the desired output will be generated, producing table rows with the correct array keys (e.g., 4722, 4922, 7522) as the first column values.
The above is the detailed content of How to Get Array Keys in a PHP Foreach Loop Correctly?. For more information, please follow other related articles on the PHP Chinese website!