- PHP array_keys
- Introduction to the PHP array_keys function
- PHP array_keys() function examples
- 1) Using the array_keys() function example
- 2) Using PHP array_keys() function with an associative array example
- Finding array keys that pass a test
- Summary
- array_keys
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 28 notes
PHP array_keys
Summary: in this tutorial, you will learn how to use the PHP array_keys() function to get the keys of an array.
Introduction to the PHP array_keys function
The PHP array_keys() function accepts an array and returns all the keys or a subset of the keys of the array.
array_keys ( array $array , mixed $search_value , bool $strict = false ) : array
Code language: PHP (php)
- $array is the input array.
- $search_value specifies the value of the keys to search for.
- $strict if it sets to true , the array_keys() function uses the identical operator (===) for matching the search_value with the array keys. Otherwise, the function uses the equal opeartor (==) for matching.
The array_keys() function returns an array that contains all the keys in the input array.
PHP array_keys() function examples
Let’s take some examples of using the array_keys() function.
1) Using the array_keys() function example
The following example shows how to get all keys of an indexed array:
$numbers = [10, 20, 30]; $keys = array_keys($numbers); print_r($keys);
Code language: HTML, XML (xml)
Array ( [0] => 0 [1] => 1 [2] => 2 )
Code language: PHP (php)
- First, define an array that contains three numbers.
- Second, use the array_keys() function to get all the keys of the $numbers array.
- Third, display the keys.
Since the $numbers is an indexed array, the array_keys() function returns the numeric keys of the array.
The following example uses the array_keys() function to get the keys of the array whole value is 20:
$numbers = [10, 20, 30]; $keys = array_keys($numbers, 20); print_r($keys);
Code language: HTML, XML (xml)
Array ( [0] => 1 )
Code language: PHP (php)
The array_keys() function returns the key 1 because key 1 contains the value 20.
2) Using PHP array_keys() function with an associative array example
The following example illustrates how to use the array_keys() function with an associative array:
$user = [ 'username' => 'admin', 'email' => 'admin@phptutorial.net', 'is_active' => '1' ]; $properties = array_keys($user); print_r($properties);
Code language: HTML, XML (xml)
Array ( [0] => username [1] => email [2] => is_active )
Code language: PHP (php)
- First, define an associative array $user that contains three keys username , email , and is_active .
- Second, get the keys of $user array using the array_keys() function.
- Third, show the returned keys.
The following example uses the array_keys() function to get the keys whose values equal 1:
$user = [ 'username' => 'admin', 'email' => 'admin@phptutorial.net', 'is_active' => '1' ]; $properties = array_keys($user, 1); print_r($properties);
Code language: PHP (php)
Array ( [0] => is_active )
Code language: PHP (php)
The array_keys() function returns one key, which is is_active . However, the is_active contains the string ‘1’ , not the number 1 . This is because the array_keys() uses the equality (==) operator for comparison in searching by default.
To enable the strict equality comparison (===) when searching, you pass true as the third argument of the array_keys() function like this:
$user = [ 'username' => 'admin', 'email' => 'admin@phptutorial.net', 'is_active' => '1' ]; $properties = array_keys($user, 1, true); print_r($properties);
Code language: HTML, XML (xml)
Array ( )
Code language: JavaScript (javascript)
Now, the array_keys() function returns an empty array.
Finding array keys that pass a test
The following function returns the keys of an array, which pass a test specified a callback:
function array_keys_by(array $array, callable $callback): array < $keys = []; foreach ($array as $key => $value) < if ($callback($key)) < $keys[] = $key; >> return $keys; >
Code language: HTML, XML (xml)
The following example uses the array_keys_by() function above to find the keys that contain the string ‘_post’ :
$permissions = [ 'edit_post' => 1, 'delete_post' => 2, 'publish_post' => 3, 'approve' => 4, ]; $keys = array_keys_by($permissions, function ($permission) < return strpos($permission, 'post'); >); print_r($keys);
Code language: HTML, XML (xml)
Summary
array_keys
Функция array_keys() возвращает числовые и строковые ключи, содержащиеся в массиве array .
Если указан параметр filter_value , функция возвращает ключи у которых значения элементов массива совпадают с этим параметром. В обратном случае, функция возвращает все ключи массива array .
Список параметров
Массив, содержащий возвращаемые ключи.
Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.
Определяет использование строгой проверки на равенство (===) при поиске.
Возвращаемые значения
Возвращает массив со всеми ключами array .
Примеры
Пример #1 Пример использования array_keys()
$array = array( 0 => 100 , «color» => «red» );
print_r ( array_keys ( $array ));
?php
$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() — Осуществляет поиск данного значения в массиве и возвращает ключ первого найденного элемента в случае успешного выполнения
User Contributed Notes 28 notes
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.
$importantKeys = array( ‘329462291595’ => null , ‘ZZ291595’ => null );
foreach( array_keys ( $importantKeys ) as $key ) echo gettype ( $key ). «\n» ;
>
?>
will return on a 64 bits system:
integer
string
?>
but on a 32 bits system:
string
string
?>
I hope it will save someone the huge headache I had 🙂
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:
$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 ));
?>
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.
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()
)
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.
$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
—-
expected to see:
dude dude dude
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.
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:
$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
# 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:
?php>
$a = array(
«first_index» => «This is the first element» ,
true => 3 ,
false => 2 ,
4.5 => ‘Something’ ,
«08» => 5 ,
«8» => 6 ,
NULL => ‘Null key’
);
Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)
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:
foreach( $array as $key => $val ) $flattenedKeysArray [] = $key ;
if( is_array ( $val ))
array_walk_keys ( $val , $key , $flattenedKeysArray );
>
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):
$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:
I wrote a function to get keys of arrays recursivelly.
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
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.
function 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):
$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’],