Backend Development 4 min read

PHP array_keys() Function: Usage, Parameters, Return Values, and Advanced Examples

This article explains the PHP array_keys() function, detailing its signature, required and optional parameters, return behavior, basic and advanced usage examples—including retrieving the first matching key and using strict type comparison—while noting performance considerations for large arrays.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP array_keys() Function: Usage, Parameters, Return Values, and Advanced Examples

array_keys() is a commonly used PHP function that returns all the keys of an array.

Function signature: array_keys($array, $search_value = null, $strict = false)

Parameters:

$array (required): the input array.

$search_value (optional): value to search for.

$strict (optional): if true, performs strict type comparison; default false.

Return value: If $search_value is omitted, returns an array of all keys. If provided, returns keys whose values match $search_value .

Basic usage example:

<?php
$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry', 'd' => 'durian');
$keys = array_keys($array);
print_r($keys);
$banana_keys = array_keys($array, 'banana');
print_r($banana_keys);
?>

Output:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
Array
(
    [0] => b
)

Advanced usage – first matching key:

<?php
$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry', 'd' => 'durian', 'e' => 'banana');
$banana_keys = array_keys($array, 'banana');
if (count($banana_keys) > 0) {
    $first_banana_key = current(array_slice($banana_keys, 0, 1));
    echo 'First matching key: ' . $first_banana_key;
}
?>

Output:

First matching key: b

Strict comparison example:

<?php
$array = array('1' => 'apple', '2' => 'banana', '3' => 'cherry');
// Without strict comparison
$keys = array_keys($array, '2');
echo 'Without strict: ';
print_r($keys);
// With strict comparison
$keys = array_keys($array, '2', true);
echo 'With strict: ';
print_r($keys);
?>

Output:

Without strict: Array ( [0] => 2 )
With strict: Array ( )

Summary: array_keys() efficiently retrieves keys from an array, supports optional value searching and strict type comparison, but should be used cautiously with large arrays to avoid memory or performance issues.

php-functionsarray-manipulationarray_keys
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.