PHP array_keys() function
The array_keys()
function in PHP is used to retrieve all the keys from an array and return them in a new array. You can optionally filter the keys by specifying a particular value to return only the keys that correspond to that value. This function works for both associative arrays (with string keys) and indexed arrays (with numeric keys).
Syntax:
Parameters:
- $array: The input array from which to retrieve the keys.
- $value (optional): If specified,
array_keys()
will return only the keys that have this value. - $strict (optional): If set to
true
, the function will use strict comparison (===
) to compare values, meaning both the value and its type must match exactly. The default isfalse
(loose comparison).
Return Value:
- The function returns an indexed array of keys from the input array. If
$value
is provided, only keys associated with that value will be returned.
Example 1: Retrieving All Keys
In its basic form, array_keys()
returns all the keys from an array.
Output:
In this example, the function returns an array containing all the keys ("name"
, "age"
, and "email"
) from the input associative array.
Example 2: Filtering Keys by Value
You can specify a value, and array_keys()
will return only the keys that are associated with that value.
Output:
Here, array_keys()
returns only the keys where the value is 10
. These keys are 0
, 2
, and 4
.
Example 3: Strict Comparison (===
)
By default, array_keys()
performs loose comparison (==
) when comparing values. However, you can enable strict comparison (===
) by setting the third parameter to true
.
Output (Loose Comparison):
Output (Strict Comparison):
In the loose comparison, array_keys()
considers all values (1
, "1"
, 1.0
) to be equal to 1
, so it returns all the keys. With strict comparison, only the exact match (1 === 1
) is considered, so only the key "a"
is returned.
Example 4: Indexed Arrays
array_keys()
can also be used with indexed arrays to retrieve the numeric indices.
Output:
In this case, the function returns the indices (0
, 1
, 2
) of the indexed array.
Practical Usage:
array_keys()
is useful for:- Extracting all keys from an associative array, especially when you need to iterate over keys instead of values.
- Filtering keys based on a specific value, allowing you to quickly find the keys associated with that value.
- Handling scenarios where you need to work with arrays of keys for further operations (e.g., inverting keys and values).
Summary:
array_keys($array)
returns an array containing all the keys from the input array.- If a specific
$value
is provided, only keys associated with that value are returned. - The function supports strict comparison (
===
) to compare both the value and its type. - It works for both associative arrays and indexed arrays.
This function is versatile for extracting and filtering keys, making it a useful tool when working with arrays in PHP.