Home > Backend Development > PHP Tutorial > How Do I Retrieve Keys from an Associative Array in PHP?

How Do I Retrieve Keys from an Associative Array in PHP?

Patricia Arquette
Release: 2024-12-11 13:19:17
Original
601 people have browsed it

How Do I Retrieve Keys from an Associative Array in PHP?

Getting Keys from an Associative Array in PHP

Introduction

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.

Solution

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
}
Copy after login

Here, the $key variable will hold the current key, while the $value variable will hold the corresponding value.

Example

Consider the following associative array:

$arr = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10"
);
Copy after login

Using the foreach loop mentioned above, you can obtain the following output:

1
2
10
Copy after login

PHP Documentation

As documented in the official PHP documentation, the correct syntax for iterating over an associative array with keys is:

foreach ($array as $key => $value) {
    // ...
}
Copy after login

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!

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