Hướng dẫn what are php keys? - Phím php là gì?

(Php 4, Php 5, Php 7, Php 8)

Khóa - Lấy chìa khóa từ một mảngFetch a key from an array

Sự mô tả

phím (mảng | đối tượng $array): int | chuỗi | null(array|object $array): int|string|null

Thông số

array

Mảng.

Trả về giá trị

Chức năng khóa () chỉ đơn giản là trả về khóa của phần tử mảng hiện đang được chỉ ra bởi con trỏ bên trong.Nó không di chuyển con trỏ theo bất kỳ cách nào.Nếu con trỏ bên trong các điểm vượt quá cuối của danh sách các phần tử hoặc mảng trống, key () trả về null.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.

Ví dụ

Ví dụ #1 phím () ví dụ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);
}
?>

Ví dụ trên sẽ xuất ra:

Xem thêm

  • Dòng điện () - Trả lại phần tử hiện tại trong một mảng
  • Tiếp theo () - Nâng cao con trỏ bên trong của một mảng
  • Array_Key_First () - Nhận khóa đầu tiên của một mảng
  • cho mỗi

lhardie ¶

8 năm trước

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.

Vinob44 tại Gmail Dot Com ¶

9 năm trước

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

array0

array1

array2

Fatbat ¶

11 năm trước

array3

array4

Md tahazzot ¶

2 năm trước

array6

array7

array8

danielmadsv tại gmail dot com ¶

3 năm trước

null0

null1

null2

null3