Home  >  Article  >  Backend Development  >  How to query the key of an array element in php

How to query the key of an array element in php

WBOY
WBOYOriginal
2022-03-29 12:16:344372browse

In PHP, you can use the key() function to query the key of an array element. This function is used to return the key name of the element currently pointed to by the internal pointer of the array. If an error occurs, the returned result is FALSE, and the syntax is " key (specified array)".

How to query the key of an array element in php

The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.

How to query the key of an array element in php

key() function returns the key name of the element currently pointed to by the internal pointer of the array.

If an error occurs, the function returns FALSE.

The key() function is used to obtain the key name of the current element in the array.

There is a pointer inside each PHP array, which points to an element of the array. The pointed element is the "current element". The current element of an array can be returned through the current() function.

The syntax is:

key(array)

The example is as follows:

<?php
$info = array(
    &#39;name&#39; => &#39;中文网&#39;,
    &#39;url&#39; => &#39;http&#39;,
    &#39;age&#39; => 8,
    &#39;desc&#39; => &#39;一个学习编程的网站&#39;,
    &#39;course&#39; => &#39;PHP教程&#39;
);
for ($i=0,$len=count($info); $i<$len; $i++) {
    echo key($info) . "<br/>";  //输出内部指针指向的当前元素的键
    next($info);  // 将数组内部指针向后移动一位
}
?>

The result of executing the above program is:

name
url
age
desc
course

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to query the key of an array element in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn