Array php получить значение ключа

array_keys

Функция array_keys() возвращает числовые и строковые ключи, содержащиеся в массиве array .

Если указан необязательный параметр search_value , функция возвращает только ключи, совпадающие с этим параметром. В обратном случае, функция возвращает все ключи массива array .

Список параметров

Массив, содержащий возвращаемые ключи.

Если указано, будут возвращены только ключи, содержащие данное значение.

Определяет использование строгой проверки на равенство (===) при поиске.

Возвращаемые значения

Возвращает массив со всеми ключами array .

Примеры

Пример #1 Пример использования array_keys()

$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_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.
Читайте также:  Python with open binary file

Examples

Example #1 key() example

$array = array(
‘fruit1’ => ‘apple’ ,
‘fruit2’ => ‘orange’ ,
‘fruit3’ => ‘grape’ ,
‘fruit4’ => ‘apple’ ,
‘fruit5’ => ‘apple’ );

// 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 )

Читайте также:  Python try except indexerror

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:

    Unlock Full Access 50% off

    COLOR PICKER

    colorpicker

    Join our Bootcamp!

    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.

    Источник

Оцените статью