Home > Backend Development > PHP Tutorial > How Do I Access Keys in PHP Associative Arrays?

How Do I Access Keys in PHP Associative Arrays?

Patricia Arquette
Release: 2024-12-08 04:33:11
Original
571 people have browsed it

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"
);
Copy after login

Using the following code, you can access the values of the array:

foreach ($arr as $v) {
    echo $v;    // Value1, Value2, Value10
}
Copy after login

To obtain the keys of the array, you can modify the loop as follows:

foreach ($arr as $key => $value) {
    echo $key;    // 1, 2, 10
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template