PHP array_keys() - Complete Guide with Examples

Mahesh Mahesh Waghmare
7 min read

The array_keys() function returns all the keys from an array, optionally filtered by a specific value. It’s essential for array manipulation, key extraction, and data processing in PHP.

This comprehensive guide covers everything you need to know about array_keys(), from basic usage to advanced filtering and real-world applications.

Introduction to array_keys()

array_keys() extracts and returns all keys from an array. It can also filter keys based on a specific value, making it useful for finding which keys contain a particular value.

Key Characteristics:

  • Returns numeric array of keys
  • Preserves key order
  • Can filter by value
  • Works with indexed and associative arrays
  • Supports strict comparison

Common Use Cases:

  • Extract all keys from array
  • Find keys with specific value
  • Get array structure
  • Key validation
  • Data transformation

Syntax and Parameters

Function Signature

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

Parameters

$array (required):

  • The input array
  • Can be indexed or associative

$search_value (optional):

  • If specified, only keys with this value are returned
  • If null, all keys are returned

$strict (optional):

  • If true, uses strict comparison (===)
  • If false, uses loose comparison (==)
  • Default: false

Return Value

Returns a numeric array containing all keys (or filtered keys) from the input array.

Advertisement

Basic Usage Examples

Get All Keys

Associative Array:

$user = [
    'name' => 'John',
    'email' => 'john@example.com',
    'age' => 30,
    'role' => 'admin'
];

$keys = array_keys($user);
// Result: [0 => 'name', 1 => 'email', 2 => 'age', 3 => 'role']

Indexed Array:

$fruits = ['apple', 'banana', 'orange'];

$keys = array_keys($fruits);
// Result: [0, 1, 2]

Mixed Array:

$data = [
    0 => 'zero',
    'one' => 1,
    2 => 'two',
    'three' => 3
];

$keys = array_keys($data);
// Result: [0 => 0, 1 => 'one', 2 => 2, 3 => 'three']

Check if Key Exists

$array = ['name' => 'John', 'age' => 30];
$keys = array_keys($array);

if (in_array('name', $keys)) {
    echo "Key 'name' exists";
}

Get Array Structure

function getArrayStructure($array) {
    return [
        'keys' => array_keys($array),
        'count' => count($array),
        'is_associative' => array_keys($array) !== range(0, count($array) - 1)
    ];
}

$info = getArrayStructure(['a' => 1, 'b' => 2, 'c' => 3]);

Filter Keys by Value

Find Keys with Specific Value

$scores = [
    'math' => 85,
    'science' => 90,
    'english' => 85,
    'history' => 75
];

// Find all subjects with score 85
$keys = array_keys($scores, 85);
// Result: [0 => 'math', 1 => 'english']

Multiple Occurrences

$data = [
    'user1' => 'active',
    'user2' => 'inactive',
    'user3' => 'active',
    'user4' => 'pending',
    'user5' => 'active'
];

// Find all active users
$activeUsers = array_keys($data, 'active');
// Result: [0 => 'user1', 1 => 'user3', 2 => 'user5']

With Different Value Types

$mixed = [
    'a' => 1,
    'b' => '1',
    'c' => 1,
    'd' => true
];

// Loose comparison (default)
$keys1 = array_keys($mixed, 1);
// Result: ['a', 'b', 'c', 'd'] - matches 1, '1', and true

// Strict comparison
$keys2 = array_keys($mixed, 1, true);
// Result: ['a', 'c'] - only matches integer 1

Strict Comparison

Loose vs Strict

Loose Comparison (default):

$data = ['a' => 1, 'b' => '1', 'c' => true];

$keys = array_keys($data, 1);
// Matches: 'a' (1), 'b' ('1'), 'c' (true)
// Result: ['a', 'b', 'c']

Strict Comparison:

$data = ['a' => 1, 'b' => '1', 'c' => true];

$keys = array_keys($data, 1, true);
// Matches only: 'a' (integer 1)
// Result: ['a']

When to Use Strict

Use strict comparison when:

  • Type matters (distinguish 1 from ‘1’)
  • Working with boolean values
  • Need precise matching
  • Data integrity is critical
$statuses = [
    'user1' => 1,      // integer
    'user2' => '1',    // string
    'user3' => true,   // boolean
    'user4' => 1       // integer
];

// Find only integer 1
$integerOnes = array_keys($statuses, 1, true);
// Result: ['user1', 'user4']
Advertisement

Common Patterns

Check if Value Exists

function hasValue($array, $value) {
    return !empty(array_keys($array, $value));
}

$data = ['a' => 1, 'b' => 2, 'c' => 3];
if (hasValue($data, 2)) {
    echo "Value 2 exists";
}

Get First Key with Value

function getFirstKeyWithValue($array, $value) {
    $keys = array_keys($array, $value);
    return !empty($keys) ? $keys[0] : null;
}

$first = getFirstKeyWithValue($data, 'target');

Count Occurrences

function countValueOccurrences($array, $value) {
    return count(array_keys($array, $value));
}

$count = countValueOccurrences($scores, 85);
// Returns: 2

Filter and Reindex

$original = ['a' => 1, 'b' => 2, 'c' => 1, 'd' => 3];

// Get keys with value 1
$keys = array_keys($original, 1);

// Create new array with only those keys
$filtered = array_intersect_key($original, array_flip($keys));
// Result: ['a' => 1, 'c' => 1]

Real-World Examples

Find User Roles

$users = [
    'john' => 'admin',
    'jane' => 'editor',
    'bob' => 'admin',
    'alice' => 'viewer',
    'charlie' => 'admin'
];

// Find all admin users
$admins = array_keys($users, 'admin');
// Result: ['john', 'bob', 'charlie']

Filter Configuration

$config = [
    'debug' => true,
    'cache' => false,
    'logging' => true,
    'analytics' => false
];

// Get all enabled features
$enabled = array_keys($config, true);
// Result: ['debug', 'logging']

Data Validation

function validateRequiredFields($data, $required) {
    $missing = [];
    
    foreach ($required as $field) {
        if (!in_array($field, array_keys($data))) {
            $missing[] = $field;
        }
    }
    
    return $missing;
}

$data = ['name' => 'John', 'email' => 'john@example.com'];
$required = ['name', 'email', 'phone'];
$missing = validateRequiredFields($data, $required);
// Result: ['phone']

Group by Value

function groupKeysByValue($array) {
    $grouped = [];
    $values = array_unique(array_values($array));
    
    foreach ($values as $value) {
        $grouped[$value] = array_keys($array, $value);
    }
    
    return $grouped;
}

$scores = [
    'math' => 85,
    'science' => 90,
    'english' => 85,
    'history' => 75
];

$grouped = groupKeysByValue($scores);
/*
Result:
[
    85 => ['math', 'english'],
    90 => ['science'],
    75 => ['history']
]
*/

array_values()

Get values instead of keys:

$array = ['a' => 1, 'b' => 2, 'c' => 3];
$keys = array_keys($array);   // ['a', 'b', 'c']
$values = array_values($array); // [1, 2, 3]

array_key_exists()

Check if specific key exists:

$array = ['name' => 'John', 'age' => 30];

// Using array_keys
$keys = array_keys($array);
$exists = in_array('name', $keys);

// Better: Using array_key_exists
$exists = array_key_exists('name', $array);

array_flip()

Swap keys and values:

$array = ['a' => 1, 'b' => 2];
$flipped = array_flip($array);
// Result: [1 => 'a', 2 => 'b']

// Get keys of original as values
$keys = array_keys($array);
$values = array_values($array);

Combined Usage

$data = ['a' => 1, 'b' => 2, 'c' => 1];

// Get all keys
$allKeys = array_keys($data);

// Get keys with value 1
$keysWithOne = array_keys($data, 1);

// Get values for those keys
$values = array_intersect_key($data, array_flip($keysWithOne));

Best Practices

  1. Use array_key_exists() for single key checks (faster)
  2. Use strict comparison when type matters
  3. Combine with array_values() for key-value operations
  4. Cache results if used multiple times
  5. Document filtering logic for complex cases

Conclusion

array_keys() is essential for:

  • Extracting array keys
  • Finding keys by value
  • Array structure analysis
  • Data filtering

Key Takeaways:

  • Returns all keys without filter
  • Filters keys by value when specified
  • Supports strict/loose comparison
  • Works with all array types
  • Combine with other array functions

Mastering array_keys() will enhance your PHP array manipulation capabilities.

Advertisement
Mahesh Waghmare

Written by Mahesh Waghmare

I bridge the gap between WordPress architecture and modern React frontends. Currently building tools for the AI era.

Follow on Twitter

Read Next