Php текущий ключ массив

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 ) : arrayCode 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’ );

// этот цикл выведет все ключи ассоциативного массива,
// значения которых равны «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 );

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