- 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
- Php текущий ключ массив
- Описание
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Смотрите также
- User Contributed Notes 5 notes
- array_key_first
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 2 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
Php текущий ключ массив
key — Выбирает ключ из массива
Описание
key() возвращает индекс текущего элемента массива.
Список параметров
Возвращаемые значения
Функция key() просто возвращает ключ того элемента массива, на который в данный момент указывает внутренний указатель массива. Она не сдвигает указатель ни в каком направлении. Если внутренний указатель указывает вне границ массива или массив пуст, key() возвратит null .
Список изменений
Версия | Описание |
---|---|
8.1.0 | Вызов функции в объекте ( object ) объявлен устаревшим. Либо сначала преобразуйте объект ( object ) в массив ( array ) с помощью функции get_mangled_object_vars() , либо используйте методы, предоставляемые классом, реализующим интерфейс Iterator , например, ArrayIterator . |
7.4.0 | Экземпляры классов SPL теперь обрабатываются как пустые объекты, не имеющие свойств, вместо вызова метода Iterator с тем же именем, что и эта функция. |
Примеры
Пример #1 Пример использования key()
$array = array(
‘fruit1’ => ‘apple’ ,
‘fruit2’ => ‘orange’ ,
‘fruit3’ => ‘grape’ ,
‘fruit4’ => ‘apple’ ,
‘fruit5’ => ‘apple’ );
?php
// этот цикл выведет все ключи ассоциативного массива,
// значения которых равны «apple»
while ( $fruit_name = current ( $array )) if ( $fruit_name == ‘apple’ ) echo key ( $array ), «\n» ;
>
next ( $array );
>
?>
Результат выполнения данного примера:
Смотрите также
- current() — Возвращает текущий элемент массива
- next() — Перемещает указатель массива вперёд на один элемент
- array_key_first() — Получает первый ключ массива
- foreach
User Contributed Notes 5 notes
Note that using key($array) in a foreach loop may have unexpected results.
When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)
I was incorrectly using:
foreach( $array as $value )
$mykey = key ( $array );
>
?>
and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)
CORRECT:
foreach( $array as $key => $value )
$mykey = $key ;
>
A noob error , but felt it might help someone else out there .
Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this
while ( $fruit_name = current ( $array ))
echo key ( $array ). ‘
‘ ;
next ( $array );
>
// the way will be break loop when arra(‘2’=>0) because its value is ‘0’, while(0) will terminate the loop
// correct approach
while ( ( $fruit_name = current ( $array )) !== FALSE )
echo key ( $array ). ‘
‘ ;
next ( $array );
>
//this will work properly
?>
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.
reset ( $x ); // optional.
arsort ( $x );
$key_of_max = key ( $x ); // returns the index.
?>
(Editor note: Or just use the array_keys function)
Make as simple as possible but not simpler like this one 🙂
In addition to FatBat’s response, if you’d like to find out the highest key in an array (assoc or not) but don’t want to arsort() it, take a look at this:
$arr = [ ‘3’ => 14 , ‘1’ => 15 , ‘4’ => 92 , ’15’ => 65 ];
$key_of_max = array_search ( max ( $arr ) , $arr );
- Функции для работы с массивами
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
array_key_first
Get the first key of the given array without affecting the internal array pointer.
Parameters
Return Values
Returns the first key of array if the array is not empty; null otherwise.
Examples
Example #1 Basic array_key_first() Usage
$firstKey = array_key_first ( $array );
The above example will output:
Notes
There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys() , but that may be rather inefficient. It is also possible to use reset() and key() , but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:
if (! function_exists ( ‘array_key_first’ )) function array_key_first (array $arr ) foreach( $arr as $key => $unused ) return $key ;
>
return NULL ;
>
>
?>?phpSee Also
- array_key_last() — Gets the last key of an array
- reset() — Set the internal pointer of an array to its first element
User Contributed Notes 2 notes
Another way to get first array key with PHP older than 7.3.
$array = [ ‘one’ , ‘two’ , ‘three’ ];
$array2 = [ ‘one’ => ‘Number one’ , ‘two’ => ‘Number two’ ];reset ( $array ); // go to first array
echo key ( $array ); // get its key (first array)
// expect 0.reset ( $array2 );
echo key ( $array2 );
// expect one.One-liner polyfill (php version < 7.3.0)
function array_key_first (array $array )
return key ( array_slice ( $array , 0 , 1 ));
>- Array Functions
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each