PHP 7.4.3 released

# array_keys

(PHP 4, PHP 5, PHP 7)

array_keysReturn all the keys or a subset of the keys of an array

### Description

array_keys ( array `\$array` ) : array
array_keys ( array `\$array` , mixed `\$search_value` [, bool `\$strict` = `FALSE` ] ) : array

array_keys() returns the keys, numeric and string, from the `array`.

If a `search_value` is specified, then only the keys for that value are returned. Otherwise, all the keys from the `array` are returned.

### Parameters

`array`

An array containing keys to return.

`search_value`

If specified, then only keys containing these values are returned.

`strict`

Determines if strict comparison (===) should be used during the search.

### Return Values

Returns an array of all the keys in `array`.

### Examples

Example #1 array_keys() example

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

The above example will output:

```Array
(
 => 0
 => color
)
Array
(
 => 0
 => 3
 => 4
)
Array
(
 => color
 => size
)
```

• array_values() - Return all the values of an array
• array_combine() - Creates an array by using one array for keys and another for its values
• array_key_exists() - Checks if the given key or index exists in the array
• array_search() - Searches the array for a given value and returns the first corresponding key if successful add a note

### User Contributed Notes 28 notes

95
pat dot leblanc at gmail dot com
8 years ago
``` It's worth noting that if you have keys that are long integer, such as '329462291595', they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.for example:<?php \$importantKeys = array('329462291595' =>null, 'ZZ291595' => null);foreach(array_keys(\$importantKeys) as \$key){    echo gettype(\$key)."\n";}?>will return on a 64 bits system:<?php     integer    string?>but on a 32 bits system:<?php     string    string?>I hope it will save someone the huge headache I had :) ```
55
Sven (bitcetera.com)
14 years ago
``` Here's how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:<?php  \$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');  // get the first key: returns 'first'  print array_shift(array_keys(\$array));  // get the last key: returns 'third'  print array_pop(array_keys(\$array));  // get the first value: returns '111'  print array_shift(array_values(\$array));  // get the last value: returns '333'  print array_pop(array_values(\$array));?> ```
12
phpnet at holodyn dot com
6 years ago
``` Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.  Invalid:echo array_shift( array_keys( array('a' => 'apple') ) );Valid:\$keys = array_keys( array('a' => 'apple') );echo array_shift( \$keys );But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:echo array_shift( ( array_keys( array('a' => 'apple') ) ) );However I would expect in time the PHP team will modify the rules of parentheses. ```
14
Ian (maxianos at hotmail dot com)
5 years ago
``` There's a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.Here's a way to find all the keys from a multidimensional  array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.NOTE: If the sub element isn't an array, it will be ignore.<?phpfunction array_keys_recursive(\$myArray, \$MAXDEPTH = INF, \$depth = 0, \$arrayKeys = array()){       if(\$depth < \$MAXDEPTH){            \$depth++;            \$keys = array_keys(\$myArray);            foreach(\$keys as \$key){                if(is_array(\$myArray[\$key])){                    \$arrayKeys[\$key] = array_keys_recursive(\$myArray[\$key], \$MAXDEPTH, \$depth);                }            }        }        return \$arrayKeys;    }?>EXAMPLE:input:array(    'Player' => array(        'id' => '4',        'state' => 'active',    ),    'LevelSimulation' => array(        'id' => '1',        'simulation_id' => '1',        'level_id' => '1',        'Level' => array(            'id' => '1',            'city_id' => '8',            'City' => array(                'id' => '8',                'class' => 'home',            )        )    ),    'User' => array(        'id' => '48',        'gender' => 'M',        'group' => 'user',        'username' => 'Hello'    ))output:array(    'Player' => array(),    'LevelSimulation' => array(        'Level' => array(            'City' => array()        )    ),    'User' => array()) ```
12
el dot quick at gmail dot com
8 years ago
``` Sorry for my english... I wrote a function to get keys of arrays recursivelly... <?php     function recursive_keys(\$input, \$search_value = null){         \$output = (\$search_value !== null ? array_keys(\$input, \$search_value) : array_keys(\$input)) ;         foreach(\$input as \$sub){             if(is_array(\$sub)){                 \$output = (\$search_value !== null ? array_merge(\$output, recursive_keys(\$sub, \$search_value)) : array_merge(\$output, recursive_keys(\$sub))) ;             }         }         return \$output ;     } ?> I hope it will be usefull Regards ```
zammit dot andrew at gmail dot com
6 years ago
``` If an array is empty (but defined), or the \$search_value is not found in the array, an empty array is returned (not false, null, or -1). This may seem intuitive, especially given the documentation says an array is returned, but I needed to sanity test to be sure:<?php\$emptyArray = array();var_dump(array_keys(\$emptyArray,99)); // array (size=0) \ empty\$filledArray = array(11,22,33,42);var_dump(array_keys(\$filledArray,99)); // array (size=0) \ empty?> ```
jochem
14 years ago
``` might be worth noting in the docs that not all associative (string) keys are a like, output of the follow bit of code demonstrates - might be a handy introduction to automatic typecasting in php for some people (and save a few headaches): <?php \$r = array("0"=>"0","1"=>"1","" =>"2"," "=>"3"); echo 'how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")',"\n-----------\n"; var_dump(\$r); print_r(\$r); var_export(\$r); echo "\n-----------\n",'var_dump("0","1",""," ") = ',"\n-----------\n"; var_dump("0","1",""," "); ?> OUTPUTS: how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3") ----------- array(4) {   =>   string(1) "0"   =>   string(1) "1"   [""]=>   string(1) "2"   [" "]=>   string(1) "3" } Array (      => 0      => 1     [] => 2     [ ] => 3 ) array (   0 => '0',   1 => '1',   '' => '2',   ' ' => '3', ) ----------- var_dump("0","1",""," ") = ----------- string(1) "0" string(1) "1" string(0) "" string(1) " " ```
Paul Hirsch
4 years ago
``` It is worth noting that array_keys does not maintain the data-type of the keys when mapping them to a new array.  This created an issue with in_array and doing  a lookup on characters from a string.  NOTE:  my lookup \$array has a full map of numbers and characters - upper and lower - to do an simple faux encryption with.<?php\$array = array(     'e' => 'ieio'    ,'1' => 'one'    ,'2' => 'two'    ,'0' => 'zero');var_dump(\$array);\$keys = array_keys(\$array);var_dump(\$keys);\$string = '1e0';for (\$i = 0; \$i < strlen(\$string); \$i++) {    if (in_array(\$string[\$i],\$keys,'strict')) echo 'dude ';    else echo 'sweet ';}?>Outputs:array (size=4)  'e' => string 'ieio' (length=4)  1 => string 'one' (length=3)  2 => string 'two' (length=3)  0 => string 'zero' (length=4)array (size=4)  0 => string 'e' (length=1)  1 => int 1  2 => int 2  3 => int 0sweet dude sweet ----  expected to see:dude dude dude ```
Hayley Watson
12 years ago
``` An alternative to RQuadling at GMail dot com's array_remove() function:<?phpfunction array_remove(array \$array, \$value, \$strict=false){    return array_diff_key(\$array, array_flip(array_keys(\$array, \$value, \$strict)));}?> ```
ferrerna at gmail dot com
11 years ago
``` Here's a function I needed to collapse an array, in my case from a database query.  It takes an array that contains key-value pairs and returns an array where they are actually the key and value.<?phpfunction array_collapse(\$arr, \$x, \$y) {    \$carr = array();    while (\$el = current(\$arr)) {        \$carr[ \$el[\$x] ] = \$el[\$y];        next(\$arr);    }    return \$carr;}?>Example usage (pseudo-database code):<?php\$query = db_query('SELECT name, value FROM properties');\$result = db_returnAll(\$query);/* This will return an array like so:[   ['name' -> 'color', 'value' -> 'blue'],   ['name' -> 'style', 'value' -> 'wide-format'],   ['name' -> 'weight', 'value' -> 3.6],   ['name' -> 'name', 'value' -> 'Waerdthing']]*/\$propArr = array_collapse(\$result, 'name', 'value');/* Now this array looks like:[   ['color' -> 'blue'],   ['style' -> 'wide-format'],   ['weight' -> 3.6],   ['name' -> 'Waerdthing'],*/?>I found this handy for using with json_encode and am using it for my project http://squidby.com ```
rodrigo at NOSPAM dot dhweb dot com dot br
17 years ago
``` [Editor's note: For a complete solution to the printing of complex structures or hashes, see the PEAR::Var_Dump package: http://pear.php.net/package-info.php?pacid=103 , use "pear install Var_Dump" to get it] This function will print all the keys of a multidimensional array in html tables. It will help to debug when you don�t have control of depths. <?php function show_keys(\$ar){    echo "<table width='100%' border='1' bordercolor='#6699CC' cellspacing='0' cellpadding='5'><tr valign='top'>";       foreach (\$ar as \$k => \$v ) {          echo "<td align='center' bgcolor='#EEEEEE'>            <table border='2' cellpadding='3'><tr><td bgcolor='#FFFFFF'><font face='verdana' size='1'>               " . \$k . "            </font></td></tr></table>";            if (is_array(\$ar[\$k])) {               show_keys (\$ar[\$k]);          }          echo "</td>";       }    echo "</tr></table>"; } // Multidimensional array -> \$arvore = array(); \$arvore['1'] = array(); \$arvore['1']['1.1'] = array('1.1.1', '1.1.2', '1.1.3'); \$arvore['1']['1.2'] = array('1.2.1', '1.2.2', '1.2.3'); \$arvore['1']['1.3'] = array('1.3.1', '1.3.2', '1.3.3'); \$arvore['2'] = array(); \$arvore['2']['2.1'] = array('2.1.1', '2.1.2', '2.1.3'); \$arvore['2']['2.2'] = array('2.2.1', '2.2.2', '2.2.3'); \$arvore['2']['2.3'] = array('2.3.1', '2.3.2', '2.3.3'); \$arvore['3'] = array(); \$arvore['3']['3.1'] = array('3.1.1', '3.1.2', '3.1.3'); \$arvore['3']['3.2'] = array('3.2.1', '3.2.2', '3.2.3'); \$arvore['3']['3.3'] = array('3.3.1', '3.3.2'=>array('3.3.2.1', '3.3.2.2'), '3.3.3'); // <- show_keys(\$arvore); ?> ```
vesely at tana dot it
14 years ago
``` The position of an element.One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output "yes, we have bananas at position 0".<?php\$a = array("banana" => "yellow", "apple" = "red");\$k = get_some_fruit();if (isset(\$a[\$k])){   list(\$pos) = array_keys(array_keys(\$a), \$k);   print "yes, we have {\$k}s at position \$pos\n";}?>Not amazingly efficient, but I see no better alternative. ```
sip at email dot ee
16 years ago
``` Note, that using array_key_exists() is rather inefficient. The overhead associated with calling a function makes it slower, than using isset(\$array[\$key]), instead of array_key_exists(\$key, \$array)using isset() is usually about 1.3 times faster, according to my tests. ```
ru dot dy at gmx dot net
14 years ago
``` I was looking for a function that simply unset a variable amout of values from a one-dimensional array by key. I ended up with this (returns the array itself if no further parameter than the array is given, false with no params - does not change the source array) usage: array_remove(array \$input [, mixed key ...])<?php  function array_remove() {    if (\$stack = func_get_args()) {      \$input = array_shift(\$stack);      foreach (\$stack as \$key) {        unset(\$input[\$key]);      }      return \$input;    }    return false;  }?>Test:<?php  \$a = array('a'=>'fun', 'b'=>3.14, 'sub'=> array('1', '2', '3'), 'd'=>'what', 'e' => 'xample', 5 => 'x');  print_r(\$a);  print_r(array_remove(\$a, 'd', 'b', 5, 'sub'));?>Output: Array(    [a] => fun    [b] => 3.14    [sub] => Array        (             => 1             => 2             => 3        )    [d] => what    [e] => xample     => x)Array(    [a] => fun    [e] => xample)Hope this helps someone. ```
izzecold at live dot de
8 years ago
``` <?php/* A Function created by myself for checking multiple array keysFor Example u got an Array like \$_SESSION and u wanna know if the keys 'user','pass','email' and 'type' exists.*/function mKeyChecker(\$arr,\$keys=array()) {    if(count(\$keys) > 1) {        \$valid_keys = 0;        foreach(\$keys as \$key) {            if(array_key_exists(\$key,\$arr)) \$valid_keys++;        }        if(\$valid_keys == count(\$keys)) {            return true;        } else {            return false;        }    } else if(count(\$keys) == 1) {        if(array_key_exists(\$key,\$arr)) {            return true;        } else {            return false;        }    } else {        return false;    }}// Execution Exampleif(mKeyChecker(\$_SESSION,array('id','user','email','type'))) {    echo "is!";} else {    echo "not!";    }?> ```
Md. Abutaleb
4 days ago
``` <?php  # array_keys() also return the key if it's boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array: \$a = array(      "first_index" => "This is the first element",       true => 3,       false => 2,       4.5 => 'Something',       "08" => 5,       "8" => 6,       NULL => 'Null key'    );print_r(array_keys(\$a));Array(     => first_index     => 1     => 0     => 4     => 08     => 8     => )?> ```
creator at mindcreations dot com
12 years ago
``` This function will extract keys from a multidimensional array <?php function multiarray_keys(\$ar) {                 foreach(\$ar as \$k => \$v) {         \$keys[] = \$k;         if (is_array(\$ar[\$k]))             \$keys = array_merge(\$keys, multiarray_keys(\$ar[\$k]));     }     return \$keys; } ?> Example code: <?php \$array = array("color" => array("1stcolor" => "blue", "2ndcolor" => "red", "3rdcolor" => "green"),                "size"  => array("small", "medium", "large")); echo "<pre>"; print_r(\$array); echo "</pre>"; echo "<pre>"; print_r(multiarray_keys(\$array)); echo "</pre>"; ?> Example output: Array (     [color] => Array         (             [1stcolor] => blue             [2ndcolor] => red             [3rdcolor] => green         )     [size] => Array         (              => small              => medium              => large         ) ) Array (      => color      => 1stcolor      => 2ndcolor      => 3rdcolor      => size      => 0      => 1      => 2 ) ```
17 years ago
``` All the cool notes are gone from the site. Here's an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing. <?php while (list(\$key, \$value) = each (\${"HTTP_".\$REQUEST_METHOD."_VARS"})) {         echo \$key." = ".\$value." "; } ?> ```
-2
craig1231 at hotmail dot com
8 years ago
``` A needed a function to find the keys which contain part of a string, not equalling a string...<?phpfunction array_keys_contain(\$input, \$search_value, \$strict = false)    {        \$tmpkeys = array();        \$keys = array_keys(\$input);        foreach (\$keys as \$k)        {            if (\$strict && strpos(\$k, \$search_value) !== FALSE)                \$tmpkeys[] = \$k;            elseif (!\$strict && stripos(\$k, \$search_value) !== FALSE)                \$tmpkeys[] = \$k;        }        return \$tmpkeys;    }?> ```
-3
anthony at berglas dot org
7 years ago
``` It should be noted that the inverse function to keys (which converts keys to values) is array_count_values (which converts values to keys).  This is needed to use things like array_intersect_key.  Could go in several places.  Took me a while to figure it out. ```
-2
qeremy [atta] gmail [dotta] com
7 years ago
``` Simple ways to prefixing arrays;<?phpfunction array_keys_prefix(\$arr, \$pref = "") {    \$rarr = array();    foreach (\$arr as \$key => \$val) {        \$rarr[\$pref.\$key] = \$val;    }    return \$rarr;}function array_keys_prefix_multi(\$arr, \$pref = "") {    \$rarr = array();    foreach (\$arr as \$key => \$val) {        \$rarr[] = array_keys_prefix(\$val, \$pref);    }    return \$rarr;}// \$a = array("foo" => "FOO", "bar" => "BAR", "baz" => "BAZ"); // or\$a = array("foo" => "FOO", "bar" => "BAR", "baz" => array(1,2,3));print_r(array_keys_prefix(\$a, "my_"));// db fetch...\$products = array(    array("id" => 1, "name" => "Foo"),    array("id" => 2, "name" => "Bar"));print_r(array_keys_prefix_multi(\$products, "product_"));?>Array(    [my_foo] => FOO    [my_bar] => BAR    [my_baz] => Array        (             => 1             => 2             => 3        ))Array(     => Array        (            [product_id] => 1            [product_name] => Foo        )     => Array        (            [product_id] => 2            [product_name] => Bar        )) ```
-2
webmaster [at] baz-x [dot] at
14 years ago
``` I was looking for a function that deletes either integer keys or string keys (needed for my caching).As I didn't find a function I came up with my own solution.I didn't find the propiest function to post to so I will post it here, hope you find it useful.<?phpfunction array_extract(\$array, \$extract_type = 1){    foreach ( \$array as \$key => \$value )    {        if ( \$extract_type == 1 && is_string(\$key) )        {            // delete string keys            unset(\$array[\$key]);        }        elseif ( \$extract_type == 2 && is_int(\$key) )        {            // delete integer keys            unset(\$array[\$key]);        }    }    return \$array;}?>You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2EXTR_INT will return an array where keys are only integer whileEXTR_STRING will return an array where keys are only stringHave fun with it. ```
-1
enrique dot balleste at gmail dot com
2 years ago
``` A nice little trick to get all of the keys who have some type of value:\$keys = array_keys(\$array, !null); ```
-1
Robert C.
4 years ago
``` Keys from multi dimensional array to simple arrayWant to traverse an multi dimensional array and get the keys back in a single dimensional array? This will do the trick:<?php    public function array_walk_keys(\$array, \$parentKey = null, &\$flattened_array = null)    {        if(!is_array(\$array))            return \$array;                foreach( \$array as \$key => \$val ) {            \$flattenedKeysArray[] = \$key;                        if(is_array(\$val))                array_walk_keys(\$val, \$key, \$flattenedKeysArray);        }        return \$flattenedKeysArray;    } ```
-2
ayyappan dot ashok at gmail dot com
3 years ago
``` Post By  Sven (59892) has to be changed\$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');\$rarray = array_keys(\$array);print array_shift(\$rarray); // firstprint array_pop(\$rarray); //thridprint array_shift(\$rarray); //secondprint array_pop(\$rarray); // no resultCode below is not valid from 5.4.0 print array_shift(array_keys(\$array)); Throws Strict Standards ErrorSven code works fine till 5.3.29. From 5.4.0  the standards have been changed and results too differ.Note :Strict Standards :  Only variables should be passed by referencePlease have look of the code in different versionshttp://sandbox.onlinephpfunctions.com/code/24b5fddf14b635f1e37db69a7edffc2cbbed55e1http://sandbox.onlinephpfunctions.com/code/f695e8f81e906b4f062b66cf9b3b83b6b620464c ```
-3
neil at 11 out of 10
11 years ago
``` <?php/* * This function will return the keys of elements in the * haystack where the value is found in array needle */function array_value_intersect_keys( \$array_haystack, \$array_needle ){    \$intersected = array_intersect( \$array_haystack, \$array_needle );    return array_keys( \$intersected );}// usage \$array_haystack = array( 1 => 2, 2 => 5, 'red' => 8, 9 => 14 );\$array_needle = array( 2, 8 );\$array_keys_of_intersecting_values = array_value_intersect_keys( \$array_haystack, \$array_needle );print_r( \$array_keys_of_intersecting_values );?>returnsArray(     => 1     => red) ```
-7
Na&#39;ven Enigma
7 years ago
``` I was trying to figure out how to normalize an array with numerical keys.  Since I was doing for() for a lot of things, but only replacing it if the conditions were right, I wound up with off ball arrays I couldn't access.  That being said, I looked for a method of normalizing the array and couldn't find one, so I built my own.  I'm not sure how to go about making it recursive, but I didn't need that feature for my own, so I just went without recursion.//This will take array( => "test1",  => "test2",  => "test3") into array( => "test1",  => "test2",  => "test3") so you can access it easier.        function normalize_array(\$array){          \$newarray = array();          \$array_keys = array_keys(\$array);          \$i=0;          foreach(\$array_keys as \$key){           \$newarray[\$i] = \$array[\$key];                     \$i++;          }          return \$newarray;        } ```
-14
nodarinodo at mail dot ru
11 years ago
``` <?php    //It's a way to get keys from values )    \$es = array("is My FullName"=>"nodar chkuaselidze (nodarinodo)", "You Are" => "I don't know", "Is My Friend" => "ruxadze");    foreach(array_values(\$es) as \$ess){        echo \$ess." =>";                for(\$i =0; \$i < count(array_keys(\$es, \$ess)); \$i++){            echo reset(array_keys(\$es, \$ess))."<BR>";        } }?> ```
{"ft_lang_label":"__label__en","ft_lang_prob":0.6320222,"math_prob":0.9476784,"size":920,"snap":"2020-10-2020-16","text_gpt3_token_len":321,"char_repetition_ratio":0.19650654,"word_repetition_ratio":0.02919708,"special_character_ratio":0.59130436,"punctuation_ratio":0.21311475,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98677933,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-02-24T09:38:52Z\",\"WARC-Record-ID\":\"<urn:uuid:5086d7e6-fef7-4ce5-89e9-58deb792b0ce>\",\"Content-Length\":\"131569\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:4993e9bd-7c57-4ba1-af20-d0d025c7a89b>\",\"WARC-Concurrent-To\":\"<urn:uuid:9dcf9cf1-c5b2-4c60-ab61-ed5d4ddd5851>\",\"WARC-IP-Address\":\"185.85.0.29\",\"WARC-Target-URI\":\"https://www.php.net/array-keys\",\"WARC-Payload-Digest\":\"sha1:LPCSQ6OE6RA6DP7JZWG3CCHKZOXR2LA2\",\"WARC-Block-Digest\":\"sha1:55F7AMPST5ALODY3V6XPMYLXVWZH4U5I\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-10/CC-MAIN-2020-10_segments_1581875145910.53_warc_CC-MAIN-20200224071540-20200224101540-00199.warc.gz\"}"}