PHP array_keys() Function

PHP array_keys() function returns either all the keys of an array or the subset of the keys. Only the keys for that value are returned if a search value is specified. Otherwise, all the keys from an array are returned as the output.

In addition, it determines if strict comparison (===) should be used during the search.

Syntax

array_keys($array,value,strict)

Parameters

  1. array(required): It specifies the array.
  2. value(optional): You can specify a value, then only the keys with this value are returned.
  3. strict(optional): It is used with the value parameter.

Return value

It returns an array containing all or a subset of keys in the input array depending upon the parameters passed.

Visual RepresentationVisual Representation of PHP array_keys() Function

Example 1: How to Use array_keys() Function

<?php
$arr = [
 'a' => 'Apple', 
 'b' => 'Microsoft', 
 'c' => 'Amazon', 
 'd' => 'Alphabet', 
 'e' => 'Meta'];
 
echo 'Before array_keys() function: '; 
print_r($arr);

$result = array_keys($arr);

echo 'After array_keys() function: ';
print_r($result); 

Output

Before array_keys() function: Array
(
 [a] => Apple
 [b] => Microsoft
 [c] => Amazon
 [d] => Alphabet
 [e] => Meta
)
After array_keys() function: Array
(
 [0] => a
 [1] => b
 [2] => c
 [3] => d
 [4] => e
)

Example 2: Using the value parameterVisual Representation of Using the value parameter

<?php

$arr = ["Apple","Microsoft","Amazon","Alphabet","Meta"];

$result = array_keys($arr,"Amazon");

print_r($result);

Output

Array
(
 [0] => 2
)

Example 3: Using the strict parameter(true)Visual Representation of Using the strict parameter(true)

<?php

$arr = [100,200,300,"100",400];

print_r(array_keys($arr,"100",true));

Output

Array
(
 [0] => 3
)

In this example, fuction returns the keys where the value exactly matches “100“, considering both the value and the type. In this case, it finds only one element “100” (string) matching the search value “100” (string). Therefore, the key [3] is returned.

Example 4: Using the strict parameter(false)Visual Representation of Using the strict parameter(false)

<?php

$arr = [100,200,300,"100",400];

print_r(array_keys($arr,"100",false));

Output

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

In this example, it returns the keys where the value matches “100“, but the comparison is not type-sensitive. Here, both 100 (integer) and “100” (string) are considered as matches.  Therefore, the array [0,3] is returned.

Example 5

One thing to note about that if you have keys that are a long integer, such as ‘19214662291595’, they will be considered as such on the 64-bit system but will be of type string on the 32 bits system.

<?php

$appKeys = array('19214662291595' => null, 'AppDividend291595' => null);

foreach(array_keys($appKeys) as $key){
  echo gettype($key)."\n";
}

Output

integer
string

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.