PHP array_keys Function
last modified March 13, 2025
The PHP array_keys
function returns all the keys or a subset of
keys from an array. It's useful for extracting and working with array keys.
Basic Definition
The array_keys
function returns all the keys of an array. It can
also return keys for a specific value when the search_value parameter is used.
Syntax: array_keys(array $array, mixed $search_value = null, bool $strict = false): array
.
The function returns a new array containing the keys.
Basic array_keys Example
This shows how to extract all keys from a simple associative array.
<?php $user = [ 'name' => 'John', 'age' => 30, 'email' => 'john@example.com' ]; $keys = array_keys($user); print_r($keys);
This code outputs all keys from the $user array. The result will be: Array ( [0] => name [1] => age [2] => email ).
Searching for Specific Values
Find all keys that have a specific value in an array.
<?php $colors = [ 'red' => '#FF0000', 'green' => '#00FF00', 'blue' => '#0000FF', 'dark_red' => '#FF0000' ]; $redKeys = array_keys($colors, '#FF0000'); print_r($redKeys);
This finds all keys with the value '#FF0000'. The output will be: Array ( [0] => red [1] => dark_red ).
Using Strict Comparison
Demonstrate the difference between loose and strict comparison when searching.
<?php $data = [ 'a' => '1', 'b' => 1, 'c' => '1.0', 'd' => 1.0 ]; $looseMatch = array_keys($data, 1); $strictMatch = array_keys($data, 1, true); print_r($looseMatch); print_r($strictMatch);
With loose comparison, all elements match 1. With strict comparison, only the integer 1 matches. This shows the importance of the strict parameter.
Working with Numeric Arrays
Even numeric arrays have keys, which array_keys can extract.
<?php $fruits = ['apple', 'banana', 'cherry']; $keys = array_keys($fruits); print_r($keys);
This demonstrates that numeric arrays have sequential numeric keys. The output will be: Array ( [0] => 0 [1] => 1 [2] => 2 ).
Multidimensional Arrays
Extract keys from a multidimensional array structure.
<?php $users = [ 'user1' => ['name' => 'Alice', 'age' => 25], 'user2' => ['name' => 'Bob', 'age' => 30], 'user3' => ['name' => 'Charlie', 'age' => 35] ]; $userKeys = array_keys($users); print_r($userKeys);
This extracts the top-level keys from a multidimensional array. The output will be: Array ( [0] => user1 [1] => user2 [2] => user3 ).
Best Practices
- Memory Usage: Be mindful when working with large arrays.
- Strict Mode: Use strict comparison for precise matching.
- Key Types: Remember keys can be integers or strings.
- Performance: Consider alternatives for simple iterations.
Source
This tutorial covered the PHP array_keys
function with practical
examples showing its usage for various array key extraction scenarios.
Author
List all PHP Array Functions.