• :
  • :

PHP array_keys: How to use with examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

PHP array_keys: Detailed Guide

Description – PHP array_keys

PHP array_keys function returns all the keys or subset of keys of an array.

Function Signature

array_keys(array $array): array

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

Arguments

  • array – The input array
  • search_value – If specified, keys corresponding to the matching values are returned
  • strict – If true, the function performs a strict comparison

Return Type – PHP array_keys

The function returns an array containing all the keys.

Introduction

PHP array_keys function is a convenient function for isolating the keys of a PHP associative array. This function is usually coupled with other PHP functions like the array_search to overcome inherent drawbacks in these functions, especially if a function doesn’t keep a reference for the keys of an array.

PHP array_keys

Besides, the array_keys function returns a subset of keys for one or more values matching the search_value argument. This article explores the array_keys PHP using several examples. If you’re not familiar with the function, then stick to the end to learn this useful PHP function. So, it is time to get going.

Usage Example#1 – PHP array_keys

The example uses a PHP array and a reasonably straightforward function call to demonstrate the output.

<?php
$numbers = ["One"=>1, "Two"=>2, "Three"=>3, "Four"=>4, "Five"=>5];
 
print_r(array_keys($numbers));
 
/*
OUTPUT
Array
(
    [0] => One
    [1] => Two
    [2] => Three
    [3] => Four
    [4] => Five
)
*/
?>

Voila! The function returns the keys and saves us quite a hassle because if we were to write a function for the same functionality, it would be something like this.

<?php
$numbers = ["One"=>1, "Two"=>2, "Three"=>3, "Four"=>4, "Five"=>5];
 
$keys = [];
 
foreach($numbers as $key=>$value) {
    array_push($keys,$key);
}
 
print_r($keys);
 
/*
OUTPUT
Array
(
    [0] => One
    [1] => Two
    [2] => Three
    [3] => Four
    [4] => Five
)
*/
?>

So, instead of an explicit loop, the PHP array_keys function does the same in a one-liner. But that’s not all about the array_keys, as it also features the search_value argument, which we will see next.

The search_value – array_keys PHP

The array_keys arguments list has a search_value argument. If this argument is passed, the function returns a subset of keys. These keys have values that are similar or identical (if strict is true) to the search_value. The following example shows the use of this argument.

<?php
$developers = [
    "Anna" => "Javascript",
    "Edward" => "Java",
    "Rey" => "Python",
    "Sanjay" => "PHP",
    "Ali" => "C++",
    "Sarah" => "C#",
    "Bob" => "Android",
    "Tyson" => "PHP",
    "Greg"  => "PHP"
];
 
print_r(array_keys($developers, "PHP"));
 
/*
OUTPUT
Array
(
    [0] => Sanjay
    [1] => Tyson
    [2] => Greg
)
*/
?>

The array_keys function searches for “PHP” in the array and finds three matches. The return value is an array with keys corresponding to these matches in the input array. This feature is an excellent convenience because an equivalent implementation looks.

<?php
$developers = [
    "Anna" => "Javascript",
    "Edward" => "Java",
    "Rey" => "Python",
    "Sanjay" => "PHP",
    "Ali" => "C++",
    "Sarah" => "C#",
    "Bob" => "Android",
    "Tyson" => "PHP",
    "Greg"  => "PHP"
];
 
 
 
function getKeys($arr, $search_value = null, $strict = false) {
    $keys = [];
    foreach($arr as $key=>$value) {
        if(!$search_value) {
            array_push($keys,$key);
        }
        else {
           if(!$strict) {
                if($search_value == $value) {
                    array_push($keys,$key);
                }
           }
           else {
            if($search_value === $value) {
                array_push($keys,$key);
            }
           }
             
        }    
    }
 
    return $keys;
}
 
 
print_r(getKeys($developers));
 
/*
OUTPUT
Array
(
    [0] => Sanjay
    [1] => Tyson
    [2] => Greg
)
*/
?>

Boom! Lots of IF-ELSE and an explicit loop. Undoubtedly, reinventing the wheel is rarely appreciated in development. So, developers will always prefer the PHP array_keys.

Strict vs. Non-Strict – array_keys PHP

Strict comparison returns true for identical elements only. Such elements have the same value and datatype. A tripe equality operator === signifies strict comparison.

//Same values, same data types
"Hello World" === "Hello World" //Return TRUE
 
//Different values, same data types
"Hello" === "World" //Returns False
 
//Same values, different data types
"1" === 1 //Returns False
 
//Different values, different data types
"false" == true //Returns false

On the contrary, the non-strict comparison is flexible in terms of data types. It usually coerces types and leads to silly bugs in the code. Here’s how.

<?php
$elements = ["NULL"=>null, "ZERO"=>0,"EMPTY_STRING"=> '', "ONE"=>1, "TWO"=>"Two", "TRUE"=> true, "FALSE"=> false];
 
//Non-strict
print_r(array_keys($elements, false));
 
/*
OUTPUT
Array
(
    [0] => NULL
    [1] => ZERO
    [2] => EMPTY_STRING
    [3] => FALSE
)
*/
?>

Oops! The search_value is false (Boolean type), and the function returns other elements too. Amateur developers would scratch their heads and perhaps spend some time debugging this code. The caveat here is the non-strict comparison which allows type coercing.

So, PHP considers falsey values and treats the null, 0, and the empty string as false. On the contrary, strict comparison won’t do these implicit type conversions. Let’s double-check this in the following example.

<?php
$elements = ["NULL"=>null, "ZERO"=>0,"EMPTY_STRING"=> '', "ONE"=>1, "TWO"=>"Two", "TRUE"=> true, "FALSE"=> false];
 
//Strict
print_r(array_keys($elements, false, true));
 
/*
OUTPUT
Array
(
    [0] => FALSE
)
*/
?>

See! That’s all about strict vs. non-strict comparison. With this, the article comes to an end.

Conclusion

In this article, we have seen PHP array_keys function and its usage through examples. Besides, we have also seen the difference between strict and non-strict comparisons in PHP. If you made it up to the conclusion, then hopefully, you have grabbed the content. Stay tuned for similar articles and tutorials about PHP.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to merge 2 arrays with the same keys in PHP

PHP array_search: How to use in PHP with examples

How to use associative array keys in PHP array_map function

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.