Home  >  Article  >  Backend Development  >  Parse current in PHP (with code example)

Parse current in PHP (with code example)

autoload
autoloadOriginal
2021-04-21 09:50:103161browse

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)
  • $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);
输出:良人当归即好

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);
}
输出:     良人当归即好
        人生当苦无妨
        我有一剑
        可搬山

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!

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