array_keys() – Returns All or Selected Keys of an Array (PHP)

This article explains the PHP array_keys() function, detailing its purpose of returning numeric or string keys from an input array, describing optional parameters search_value and strict, and providing multiple code examples that illustrate basic usage, filtered key retrieval, and handling of associative arrays.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
array_keys() – Returns All or Selected Keys of an Array (PHP)

The array_keys() function in PHP returns the keys of an array, which can be either numeric or string.

If the optional search_value parameter is supplied, only the keys whose corresponding values match search_value are returned; otherwise all keys are returned. The optional strict boolean determines whether the comparison uses strict identity ( ===).

Parameters input (array): The array from which to retrieve keys. search_value (mixed, optional): The value to search for; only keys of elements equal to this value are returned. strict (bool, optional): When true, the comparison is strict ( ===).

Return value

Returns an array containing the keys from input that meet the criteria.

Example 1 – Basic usage

<?php
$array = array(
    0 => 100,
    "color" => "red"
);
print_r(array_keys($array));
?>

Output:

Array
(
    [0] => 0
    [1] => color
)

Example 2 – Using search_value

<?php
$array = array("blue", "red", "green", "blue");
print_r(array_keys($array, "blue"));
?>

Output:

Array
(
    [0] => 0
    [1] => 2
)

Example 3 – Using strict comparison

<?php
$array = array(
    "color" => array("blue", "red", "green"),
    "size" => array("small", "medium", "large")
);
print_r(array_keys($array, "blue", true));
?>

Output:

Array
(
    [0] => color
)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendfunctionsArraysarray_keys
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

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.