Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

ฟังก์ชัน key() ใน PHP

คำอธิบาย

ฟังก์ชัน key() ดึงคีย์ (key) ของสมาชิกที่ internal pointer ชี้อยู่ในปัจจุบัน

รูปแบบการใช้งาน (Syntax)

key(array)

พารามิเตอร์

  • array — อาร์เรย์ที่ต้องการใช้งาน

ค่าที่คืนกลับ

คืนค่าคีย์ของสมาชิกปัจจุบัน หรือ NULL หาก pointer อยู่นอกขอบเขต

ตัวอย่างการใช้งาน

<?php
$arr = array("Electronics", "Footwear");
echo "Key from current position = " . key($arr);
?>

ผลลัพธ์

Key from current position = 0

ตัวอย่างเพิ่มเติม (หาคีย์จากค่า)

<?php
$arr = array('one' => 'tim', 'two' => 'peter', 'three' => 'david');
while ($val = current($arr)) {
    if ($val == 'peter') {
        echo key($arr); // แสดงคีย์ของค่า peter
    }
    next($arr);
}
?>

ผลลัพธ์

two