- array_keys
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- Array php получить значение ключа
- Description
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- User Contributed Notes 5 notes
- How to loop through an associative array and get the key?
- PHP array_keys() Function
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
array_keys
Функция array_keys() возвращает числовые и строковые ключи, содержащиеся в массиве array .
Если указан необязательный параметр search_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_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
- array_search() — Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи
Array php получить значение ключа
key — Fetch a key from an array
Description
key() returns the index element of the current array position.
Parameters
Return Values
The key() function simply returns the key of the array element that’s currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns null .
Changelog
Version | Description |
---|---|
8.1.0 | Calling this function on object s is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator , such as ArrayIterator , instead. |
7.4.0 | Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. |
Examples
Example #1 key() example
$array = array(
‘fruit1’ => ‘apple’ ,
‘fruit2’ => ‘orange’ ,
‘fruit3’ => ‘grape’ ,
‘fruit4’ => ‘apple’ ,
‘fruit5’ => ‘apple’ );
?php
// this cycle echoes all associative array
// key where value equals «apple»
while ( $fruit_name = current ( $array )) if ( $fruit_name == ‘apple’ ) echo key ( $array ), «\n» ;
>
next ( $array );
>
?>
The above example will output:
See Also
- current() — Return the current element in an array
- next() — Advance the internal pointer of an array
- array_key_first() — Gets the first key of an array
- 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 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
How to loop through an associative array and get the key?
If you use array_keys() , PHP will give you an array filled with just the keys:
$keys = array_keys($arr); foreach ($keys as $key)
Alternatively, you can do this:
foreach ($arr as $key => $value)
Nobody answered with regular for loop? Sometimes I find it more readable and prefer for over foreach
So here it is:$array = array('key1' => 'value1', 'key2' => 'value2'); $keys = array_keys($array); for($i=0; $i < count($keys); ++$i) < echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n"; >/* prints: key1 value1 key2 value2 */
This is useful in some circumstances when foreach glitches out for unexplainable reasons. Good to always have at least two ways to do things.
Also useful for when you want to combine two subsequent array items together. i+=2 and then using $array[$keys[$i]].»_».$array[$keys[$i+1]] Just incase someone else has this same problem
The bugs in foreach are described here: php.net/manual/en/control-structures.foreach.php If you are using PHP 7, nested foreaches and foreach references work as intended. If you are using PHP 5, you should avoid using foreach by reference values and since all foreaches use internal array pointer ( current($Array) ) nesting foreaches or using PHP array functions can do weird things.
@jdrake That would be so funny, if randomly foreach does not work and you just have to relace by a for-loop. This is something they should have implemented in INTERCAL
PHP array_keys() Function
The array_keys() function returns an array containing the keys.
Syntax
Parameter Values
- true — Returns the keys with the specified value, depending on type: the number 5 is not the same as the string «5».
- false — Default value. Not depending on type, the number 5 is the same as the string «5».
Technical Details
Return Value: Returns an array containing the keys PHP Version: 4+ Changelog: The strict parameter was added in PHP 5.0 More Examples
Example
Using the value parameter:
Example
Using the strict parameter, false:
Example
Using the strict parameter, true:
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.