array_keys

(PHP 4, PHP 5, PHP 7, PHP 8)

array_keys返回数组中部分的或所有的键名

说明

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

array_keys() 返回 input 数组中的数字或者字符串的键名。

如果指定了可选参数 filter_value,则只返回该值的键名。否则 input 数组中的所有键名都会被返回。

参数

input

一个数组,包含了要返回的键。

filter_value

如果指定了这个参数,只有包含此值的键才会返回。

strict

判断在搜索的时候是否该使用严格的比较(===)。

返回值

返回 input 里的所有键。

示例

示例 #1 array_keys() 例子

<?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));
?>

以上示例会输出:

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

参见

  • array_values() - 返回数组中所有的值
  • array_combine() - 创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值
  • array_key_exists() - 检查数组里是否有指定的键名或索引
  • array_search() - 在数组中搜索给定的值,如果成功则返回首个相应的键名

添加备注

用户贡献的备注 27 notes

up
146
pat dot leblanc at gmail dot com
15 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 :)
up
60
Sven (bitcetera.com)
20 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));
?>
up
28
Ian (maxianos at hotmail dot com)
12 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.

<?php
function 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()
)
up
19
zammit dot andrew at gmail dot com
12 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

?>
up
6
Robert C.
10 years ago
Keys from multi dimensional array to simple array

Want 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;
    }
up
15
Paul Hirsch
11 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 0

sweet dude sweet 

----  
expected to see:
dude dude dude
up
16
phpnet at holodyn dot com
12 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.
up
6
jochem
20 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) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "1"
  [""]=>
  string(1) "2"
  [" "]=>
  string(1) "3"
}
Array
(
    [0] => 0
    [1] => 1
    [] => 2
    [ ] => 3
)
array (
  0 => '0',
  1 => '1',
  '' => '2',
  ' ' => '3',
)
-----------
var_dump("0","1",""," ") =
-----------
string(1) "0"
string(1) "1"
string(0) ""
string(1) " "
up
4
ayyappan dot ashok at gmail dot com
10 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); // first

print array_pop($rarray); //thrid

print array_shift($rarray); //second

print array_pop($rarray); // no result

Code below is not valid from 5.4.0 

print array_shift(array_keys($array)); Throws Strict Standards Error

Sven 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 reference

Please have look of the code in different versions

http://sandbox.onlinephpfunctions.com/code/24b5fddf14b635f1e37db69a7edffc2cbbed55e1

http://sandbox.onlinephpfunctions.com/code/f695e8f81e906b4f062b66cf9b3b83b6b620464c
up
13
el dot quick at gmail dot com
14 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