Detailed explanation of PHP array cursor implementation of various operations on arrays_php skills

WBOY
Release: 2016-05-16 19:59:15
Original
1243 people have browsed it

This article analyzes the various operations of PHP array cursors on arrays through examples. Share it with everyone for your reference, the details are as follows:

How to loop through an array without using foreach?

Answer: We only need to simulate foreach. When the array executes the foreach loop, there is a cursor pointing to the value of the current array loop,

Then if we can get this cursor and operate the cursor to move the cursor forward or backward, then we can implement a loop array without foreach

Go directly to the code, clear and intuitive:

<&#63;php 
$arr = array('你','若','安','好','便','是','晴','天');
//current()函数是取得游标所在数组位置的值
//next()是使游标向数组的尾部移动一格
for(;$v=current($arr);next($arr)){
  echo $v,'<br />';
}
/*
返回
你
若
安
好
便
是
晴
天
*/
//那么又如何使游标2步2步一走呢?
for(;$v=current($arr);){
  echo $v,'<br />';
  next($arr);
  next($arr);
}
//执行结果,没有反应,这是为什么呢?
//原因是前面一个循环游标已经到了数组的最尾部了
//因此,当执行current($arr)时总是返回false,
//因此第二个循环是不会执行的
//因此这里我们会用一个reset()方法来使游标重新指向数组的头部
reset($arr);
echo '<hr />';
for(;$v=current($arr);){
  echo $v,'<br />';
  next($arr);
  next($arr);
}
//那么又如何走2步,退一步呢?
reset($arr);
echo '<hr />';
for($flag=true;$v=current($arr);){
  echo $v,'<br />';
  if($flag){
    next($arr);
    next($arr);
    $flag=false;
  }else{
    prev($arr);
    $flag=true;
  }
}
/*
返回
你
安
若
好
安
便
好
是
便
晴
是
天
晴
*/
//如何倒着循环呢?
//这里要用到end()函数了,让数组的游标指向尾部
end($arr);
echo '<hr />';
for(;$v=current($arr);prev($arr)){
  echo $v,'<br />';
}
/*
返回:
天
晴
是
便
好
安
若
你
*/
//注意当数组的值等于0,false,null,undefined,""时,for循环的第二部会返回false,就会使循环终止
reset($arr);
echo '<hr />';
$arr2 = array('你','若',0,'好','便','是','晴','天');
for(;$v=current($arr2);next($arr2)){
  echo $v,'<br />';
}
/*
返回
你
若
*/
&#63;>
Copy after login

In addition to these, you can also use the key() function to get the key pointed by the cursor.

Readers who are interested in more content related to PHP arrays can check out the special topic of this site: "Summary of PHP Arrays (Arrary)"

I hope this article will be helpful to everyone in PHP programming.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template