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
Patricia ArquetteOriginal
2024-12-11 13:19:17626browse

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
}

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"
);

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

1
2
10

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) {
    // ...
}

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!

Statement:
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