Parse current in PHP (with code example)

autoload
Release: 2023-04-09 21:42:01
Original
3151 people have browsed it

Parse current in PHP (with code example)

​ When we are learning the foreach function in PHP, it is usually difficult to understand the operating principle of foreach. In fact, You can use the current() function to simulate, so that we may be able to understand the traversal principle of foreach more quickly.

First let’s take a look at the syntax:

current ($array)
Copy after login
  • $array: It can be an object or an array.

  • Return value: Returns the pointer inside the current array pointing to its "current" unit, which will point to the first value in the array during initialization.

Code example:

1. Actual use:

<?php
$a=array("良人当归即好","人生当苦无妨","我有一剑","可搬山");
echo current($a);
Copy after login
输出:良人当归即好
Copy after login

2. Simulate foreach()

Simulationforeach() also needs to use the following related functions:

  • reset() - Point the internal pointer of the array to the first element

  • next() - Point the internal pointer of the array to the first element Move one place forward

<?php
$a=array("良人当归即好","人生当苦无妨","我有一剑","可搬山");
$len=sizeof($a);
for($l=0;$l<$len;$l++){
    echo current($a)."<br>";
    if($l==$len-1){
        reset($a);
        break;
    }
    next($a);
}
Copy after login
输出:     良人当归即好
        人生当苦无妨
        我有一剑
        可搬山
Copy after login

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of Parse current in PHP (with code example). For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!