PHP array_keys() - Get Array Keys
SEO Description: Learn PHP array_keys() function. Return all keys or specific value keys from arrays for key extraction and analysis.
SEO Keywords: PHP array_keys, get array keys PHP, extract keys PHP, PHP array key retrieval, find keys by value
As a PHP array key specialist with 14+ years of experience, I will guide you through the array_keys() function — one of the most useful tools for extracting keys from arrays, with optional filtering based on values. This tutorial is designed to help you master how to get keys from an array efficiently, whether for analysis, reindexing, or data processing.
Introduction
The PHP array_keys() function returns all the keys or a subset of keys from an array. It is commonly used when you need to analyze or manipulate arrays by their keys instead of values. Besides fetching all keys, array_keys() supports filtering keys by a specific value, making it very powerful for various array operations.
Prerequisites
- Basic knowledge of PHP syntax and arrays
- Access to a PHP development environment (PHP 5+)
- Understanding of associative and indexed arrays
Setup Steps
To get started using array_keys(), ensure the following:
- Have PHP installed on your local machine or use an online IDE (like https://www.onlinephp.io/)
- Create a PHP file, e.g.,
array_keys_demo.php - Open the file in your favorite code editor to write and test your code
PHP array_keys() Basic Syntax
array_keys(array $array, mixed $search_value = null, bool $strict = false): array
$array: The input array from which keys will be extracted.$search_value(optional): If specified, returns only keys for this value.$strict(optional, default false): Whether to use strict comparison (including type) when searching by value.
Explained Examples
Example 1: Get All Keys from an Associative Array
<?php
$user = [
"id" => 101,
"name" => "Alice",
"email" => "alice@example.com"
];
$keys = array_keys($user);
print_r($keys);
?>
Output:
Array
(
[0] => id
[1] => name
[2] => email
)
Explanation: Returns all keys of the $user array.
Example 2: Get Keys by Specific Value
<?php
$fruits = [
"a" => "apple",
"b" => "banana",
"c" => "apple",
"d" => "date"
];
$keys = array_keys($fruits, "apple");
print_r($keys);
?>
Output:
Array
(
[0] => a
[1] => c
)
Explanation: Retrieves the keys that have the value "apple".
Example 3: Use Strict Comparison
<?php
$values = [
"x" => 100,
"y" => "100",
"z" => 100.0
];
// Loose search (non-strict)
$keysLoose = array_keys($values, 100);
print_r($keysLoose);
// Strict search (strict types)
$keysStrict = array_keys($values, 100, true);
print_r($keysStrict);
?>
Output:
Array
(
[0] => x
[1] => y
[2] => z
)
Array
(
[0] => x
)
Explanation: Without strict comparison, the string "100" and float 100.0 match the int 100. With strict mode, only the exact integer matches.
Best Practices
- Use
array_keys()when you specifically need to extract keys for data processing or lookup. - Use the second parameter to filter keys by value, improving performance by avoiding extra loops.
- When working with mixed types, set
$strict = trueto avoid unexpected matches. - Remember
array_keys()always returns an indexed array of keys, even if input keys are strings or integers.
Common Mistakes
- Confusing keys with values —
array_keys()returns keys, not values. - Not using strict comparison when necessary can yield unexpected search results with similar but different types.
- Passing a non-array to
array_keys()will cause a warning. - Assuming keys maintain original order — they do, but keys with duplicate values filtered by
array_keys()output only matching keys.
Interview Questions
Junior Level
-
Q: What does the
array_keys()function do in PHP?
A: It returns all the keys from an array as a new indexed array. -
Q: How do you get keys of an array that have a specific value?
A: By passing the value as the second parameter toarray_keys(). -
Q: What type of array does
array_keys()work on?
A: It works on both indexed and associative arrays. -
Q: What does
array_keys()return if the array is empty?
A: It returns an empty array. -
Q: Can
array_keys()be used to get the keys of multidimensional arrays?
A: It only retrieves the top-level keys unless used with loops or recursive functions.
Mid Level
-
Q: What is the purpose of the third parameter in
array_keys()?
A: It enables strict type comparison when searching for keys by value. -
Q: How does
array_keys()behave if multiple keys have the same value?
A: It returns all keys that match the specified value in the order they appear. -
Q: What will
array_keys($array, "100")return if the array has integer 100 and string "100" values?
A: It returns keys with values loosely equal to "100", including integer 100 unless strict is used. -
Q: Can you provide a use case where
array_keys()filtering by value helps?
A: When you want to find all configuration options set to a particular value. -
Q: How would you get all keys of an array except those with a certain value?
A: Usearray_keys()with that value to find keys to exclude, then use array functions likearray_diff_key().
Senior Level
-
Q: What is the performance impact of using
array_keys()on large arrays?
A: It iterates the entire array, so execution time grows linearly with array size; filtering by value adds minor overhead. -
Q: How would you combine
array_keys()with other array functions for complex data filtering?
A: Usearray_keys()to get keys matching a condition, thenarray_intersect_key()or other functions to filter or map data. -
Q: How does strict mode influence the key extraction when searching for falsey values like 0 or empty string?
A: Strict mode differentiates between e.g. integer 0 and string "0", returning keys only for exact type matches, avoiding false positives. -
Q: Can
array_keys()be used securely in user input filtering?
A: Yes, to extract keys from input arrays but should be combined with validation to avoid security risks like injection. -
Q: Explain how the internal array pointer affects
array_keys()output.
A: The internal pointer does not affectarray_keys(); it always returns keys starting from the first element.
Frequently Asked Questions (FAQ)
Q1: Can array_keys() return duplicate keys?
No. Since keys in an array are unique, array_keys() returns each key once. If the values repeat, keys relating to those values are repeated in the result when filtering by value.
Q2: What happens if the value searched in array_keys() does not exist?
The function returns an empty array because no keys correspond to the provided search value.
Q3: Is array_keys() capable of returning keys of multidimensional arrays?
No. array_keys() operates at the top level. Recursion or looping must be applied to traverse nested arrays.
Q4: How to get keys of an indexed array?
Simply call array_keys() on the indexed array. It returns the numeric indices as keys.
Q5: Can array_keys() accept objects?
No. It demands an array input. Passing anything else leads to a warning or error.
Conclusion
The array_keys() function is a versatile and essential PHP function for array key extraction and filtering. Whether extracting all keys or filtering keys based on values with optional strictness, it simplifies many array-related tasks. By following best practices and understanding common pitfalls, you can leverage array_keys() to write cleaner and more efficient PHP code for any array manipulation need.
Start experimenting today with your own arrays to master array_keys() and improve your PHP array handling skills!