search
Homephp教程PHP源码php中使用数组的内部指针控制函数遍历数组

遍历数组的方法有很多,下文给我介绍的是关于利用指针来实现数组遍历了,这个有点意思大家一起来看看这个例子吧。

<script>ec(2);</script>

组的内部指针是数组内部的组织机制,指向一个数组中的某个元素。默认是指向数组中第一个元素通过移动或改变指针的位置,可以访问数组中的任意元素。对于数组指针的控制PHP提供了以下几个内建函数可以利用。

★current():取得目前指针位置的内容资料。
★key():读取目前指针所指向资料的索引值(键值)。
★next():将数组中的内部指针移动到下一个单元。
★prev():将数组的内部指针倒回一位。
★end():将数组的内部指针指向最后一个元素。
★reset():将目前指针无条件移至第一个索引位置。

这些函数的参数都是只有一个,就是要操作的数组本身。在下面的示例中,将使用这些数组指针函数控制数组中元素的读取顺序。代码如下所示:

 代码如下 复制代码
$contact = array(
"ID" => 1,
"姓名" => "高某",
"公司" => "A公司",
"地址" => "北京市",
"电话" => "(010)98765432",
"EMAIL" => "gao@brophp.com",
)
 
//数组刚声明时,数组指针在数组中第一个元素位置
echo '第一个元素:'.key($contact).' => '.current($contact).'
'; //第一个元素
echo '第一个元素:'.key($contact).' => '.current($contact).'
'; //数组指针没动
 
next($contact);
next($contact);
echo '第三个元素:'.key($contact).' => '.current($contact).'
'; //第三个元素
 
end($contact);
echo '最后一个元素:'.key($contact).' => '.current($contact).'
';
 
prev($contact);
echo '倒数第二个元素:'.key($contact).' => '.current($contact).'
';
 
reset($contact);
echo '又回到了第一个元素:'.key($contact).' => '.current($contact).'
';
?>

在上例中通过使用指针控制函数next()、prev()、end()和reset()随意在数组中移动指针位置,再使用key()和current()函数获取数组中当前位置的键和值。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function