Current Location: Home> Latest Articles> Quick Methods to Print Array Keys in PHP

Quick Methods to Print Array Keys in PHP

gitbox 2025-08-08

Why Printing Only Array Keys Matters

In PHP development, arrays are one of the most commonly used data structures. During development, when debugging arrays, sometimes we only care about the keys (indexes) rather than the corresponding values. Printing only the array keys helps to better understand the array structure and facilitates further operations and analysis.

Using the array_keys Function to Print Array Keys

Function Syntax

array_keys(array $array, mixed $search_value = null, bool $strict = false): array

Parameter Explanation

$array: Required. Specifies the array to search keys from.

$search_value: Optional. Specifies the value to search for. If provided, only keys matching this value are returned.

$strict: Optional. Whether to use strict comparison (type and value must both match). Default is false.

Code Example

The following example demonstrates how to get all the keys of an array:

$array = array("first" => 1, "second" => 2, "third" => 3, "fourth" => 4);
$arrKeys = array_keys($array);
print_r($arrKeys);

Output:

Array
(
    [0] => first
    [1] => second
    [2] => third
    [3] => fourth
)

Example with $search_value Parameter

If you want to find the keys for the value 2 only, you can do the following:

$array = array("first" => 1, "second" => 2, "third" => 3, "fourth" => 4);
$arrKeys = array_keys($array, 2);
print_r($arrKeys);

Output:

Array
(
    [0] => second
)

Example with Both $search_value and $strict Parameters

When strict comparison is enabled, both type and value are considered:

$array = array("first" => 1, "second" => 2, "third" => "2", "fourth" => 4);
$arrKeys = array_keys($array, 2, true);
print_r($arrKeys);

Output:

Array
(
    [0] => second
)