In PHP, associative arrays store data in key-value pairs. When iterating over these arrays using foreach, you typically get the values. However, there may be instances when you need to retrieve the keys instead.
To iterate over an associative array and retrieve the keys, use foreach with the array's key-value pair syntax:
foreach ($arr as $key => $value) { echo $key; // 1, 2, 10 }
Here, the $key variable will hold the current key, while the $value variable will hold the corresponding value.
Consider the following associative array:
$arr = array( 1 => "Value1", 2 => "Value2", 10 => "Value10" );
Using the foreach loop mentioned above, you can obtain the following output:
1 2 10
As documented in the official PHP documentation, the correct syntax for iterating over an associative array with keys is:
foreach ($array as $key => $value) { // ... }
The above is the detailed content of How Do I Retrieve Keys from an Associative Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!