Home >Backend Development >PHP Tutorial >How Do I Access Keys in PHP Associative Arrays?
Accessing Keys in Associative Arrays
When iterating through associative arrays in PHP, you can use a traditional 'foreach' loop to access the values. However, if you want to retrieve the keys instead, there is a simple solution.
In your provided code, you have the following associative array:
$arr = array( 1 => "Value1", 2 => "Value2", 10 => "Value10" );
Using the following code, you can access the values of the array:
foreach ($arr as $v) { echo $v; // Value1, Value2, Value10 }
To obtain the keys of the array, you can modify the loop as follows:
foreach ($arr as $key => $value) { echo $key; // 1, 2, 10 }
By using the arrow (=>) syntax in the foreach loop, you can specify both the key and value variables. In this case, the '$key' variable will contain the key of the current element in each iteration.
The above is the detailed content of How Do I Access Keys in PHP Associative Arrays?. For more information, please follow other related articles on the PHP Chinese website!