array_keys

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

array_keysLiefert alle Schlüssel oder eine Teilmenge aller Schlüssel eines Arrays

Beschreibung

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

array_keys() gibt die Schlüssel (numerisch und String) des Arrays array zurück.

Ist der Parameter filter_value angegeben, werden nur die Schlüssel für diesen Wert zurückgegeben. Andernfalls werden alle Schlüssel von array zurückgegeben.

Parameter-Liste

array

Ein Array mit den zurückzugebenden Schlüsseln.

filter_value

Wenn angegeben, werden nur Schlüssel mit diesem Wert zurückgegeben.

strict

Bestimmt, ob bei der Suche ein strikter Vergleich (===) durchgeführt werden soll.

Rückgabewerte

Gibt ein Array mit allen Schlüsseln des Arrays array zurück.

Beispiele

Beispiel #1 array_keys()-Beispiel

<?php
$array = array(0 => 100, "Farbe" => "rot");
print_r(array_keys($array));

$array = array("blau", "rot", "grün", "blau", "blau");
print_r(array_keys($array, "blau"));

$array = array("Farbe" => array("blau", "rot", "grün"),
               "Größe" => array("klein", "mittel", "groß"));
print_r(array_keys($array));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [0] => 0
    [1] => Farbe
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => Farbe
    [1] => Größe
)

Siehe auch

  • array_values() - Liefert alle Werte eines Arrays
  • array_combine() - Erzeugt ein Array, indem es ein Array für die Schlüssel und ein anderes für die Werte verwendet
  • array_key_exists() - Prüft, ob ein gegebener Schlüssel in einem Array existiert
  • array_search() - Durchsucht ein Array nach einem Wert und liefert bei Erfolg den zugehörigen Schlüssel

add a note

User Contributed Notes 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