How to Extract Keys from an Associative Array in PHP

Extracting keys from an associative array is a fundamental task in PHP development. This article provides a straightforward guide on how to use PHP’s built-in array_keys() function to retrieve these keys, complete with practical code examples for both basic extraction and conditional filtering.

Using the array_keys() Function

The most efficient way to get only the keys from an associative array in PHP is by using the array_keys() function. This function takes an array as its input and returns a new indexed array containing all the key names.

Basic Syntax

array_keys(array $array, mixed $filter_value = null, bool $strict = false): array

Example: Basic Key Extraction

In this example, we have an associative array representing user profile data. We will extract only the keys (the field names) from this array.

<?php
// Define an associative array
$userProfile = [
    'username' => 'johndoe',
    'email' => 'john@example.com',
    'role' => 'administrator',
    'status' => 'active'
];

// Extract the keys
$keys = array_keys($userProfile);

// Output the result
print_r($keys);
?>

Output:

Array
(
    [0] => username
    [1] => email
    [2] => role
    [3] => status
)

Extracting Keys with Specific Values

The array_keys() function also accepts an optional second parameter. If you provide a search value, the function will only return the keys that match that specific value.

Example: Filtering Keys by Value

In this example, we extract only the keys that have a value of inactive.

<?php
$userStatuses = [
    'alice' => 'active',
    'bob' => 'inactive',
    'charlie' => 'active',
    'david' => 'inactive'
];

// Get keys where the value is 'inactive'
$inactiveUsers = array_keys($userStatuses, 'inactive');

print_r($inactiveUsers);
?>

Output:

Array
(
    [0] => bob
    [1] => david
)

Strict Type Comparison

By default, the value filtering uses loose comparison (==). If you want to use strict comparison (===) to match both the value and the data type, pass true as the third argument:

<?php
$data = [
    'a' => 10,
    'b' => '10',
    'c' => 10
];

// Strict comparison for the integer 10
$strictKeys = array_keys($data, 10, true);

print_r($strictKeys);
// Output will only include 'a' and 'c', excluding 'b' which is a string.
?>