Home Backend Development PHP Tutorial In-depth understanding of the usage of foreach statement to loop arrays

In-depth understanding of the usage of foreach statement to loop arrays

Jun 22, 2017 pm 04:01 PM
foreach cycle go deep understand statement

foreach是PHP中很常用的一个用作数组循环的控制语句

因为它的方便和易用,自然也就在后端隐藏着很复杂的具体实现方式(对用户透明)
今天,我们就来一起分析分析,foreach是如何实现数组(对象)的遍历的。
我们知道PHP是一个脚本语言,也就是说,用户编写的PHP代码最终都是会被PHP解释器解释执行,
特别的,对于PHP来说,所有的用户编写的PHP代码,都会被翻译成PHP的虚拟机ZE的虚拟指令(OPCODES)来执行,不论细节的话,就是说,我们所编写的任何PHP脚本,都会最终被翻译成一条条的指令,从而根据指令,由相应的C编写的函数来执行。

那么foreach会被翻译成什么样子呢?

foreach($arr as $key => $val){
   echo $key . '=>' . $val . "\n";
}
Copy after login

在词法分析阶段,foreach会被识别为一个TOKEN:T_FOREACH,
在语法分析阶段,会被规则:

 unticked_statement: //没有被绑定ticks的语句
   //有省略
  |  T_FOREACH '(' variable T_AS
    { zend_do_foreach_begin(&$1, &$2, &$3, &$4, 1 TSRMLS_CC); }
    foreach_variable foreach_optional_arg ')' { zend_do_foreach_cont(&$1, &$2, &$4, &$6, &$7 TSRMLS_CC); }
    foreach_statement { zend_do_foreach_end(&$1, &$4 TSRMLS_CC); }
  |  T_FOREACH '(' expr_without_variable T_AS
    { zend_do_foreach_begin(&$1, &$2, &$3, &$4, 0 TSRMLS_CC); }
    variable foreach_optional_arg ')' { zend_check_writable_variable(&$6); zend_do_foreach_cont(&$1, &$2, &$4, &$6, &$7 TSRMLS_CC); }
    foreach_statement { zend_do_foreach_end(&$1, &$4 TSRMLS_CC); }
   //有省略
;
Copy after login

仔细分析这段语法规则,我们可以发现,对于:

foreach($arr as $key => $val){
echo $key . ‘=>' . $val .”\n”;
}
Copy after login

会被分析为:

T_FOREACH '(' variable T_AS  { zend_do_foreach_begin('foreach', '(', $arr, 'as', 1 TSRMLS_CC); }
foreach_variable foreach_optional_arg(T_DOUBLE_ARROW foreach_variable)  ')' { zend_do_foreach_cont('foreach', '(', 'as', $key, $val TSRMLS_CC); }
foreach_satement {zend_do_foreach_end('foreach', 'as');}
Copy after login

然后,让我们来看看foreach_statement:
它其实就是一个代码块,体现了我们的 echo $key . ‘=>' . $val .”\n”;
T_ECHO expr;

显然,实现foreach的核心就是如下3个函数:

  1. zend_do_foreach_begin

  2. zend_do_foreach_cont

  3. zend_do_foreach_end

其中,zend_do_foreach_begin (代码太长,直接写伪码) 主要做了:
1. 记录当前的opline行数(为以后跳转而记录)
2. 对数组进行RESET(讲内部指针指向第一个元素)
3. 获取临时变量 ($val)
4. 设置获取变量的OPCODE FE_FETCH,结果存第3步的临时变量
4. 记录获取变量的OPCODES的行数

而对于 zend_do_foreach_cont来说:
1. 根据foreach_variable的u.EA.type来判断是否引用
2. 根据是否引用来调整zend_do_foreach_begin中生成的FE_FETCH方式
3. 根据zend_do_foreach_begin中记录的取变量的OPCODES的行数,来初始化循环(主要处理在循环内部的循环:do_begin_loop)

最后zend_do_foreach_end:
1. 根据zend_do_foreach_begin中记录的行数信息,设置ZEND_JMP OPCODES
2. 根据当前行数,设置循环体下一条opline, 用以跳出循环
3. 结束循环(处理循环内循环:do_end_loop)
4. 清理临时变量

当然, 在zend_do_foreach_cont 和 zend_do_foreach_end之间 会在语法分析阶段被填充foreach_satement的语句代码。

这样,就实现了foreach的OPCODES line。
比如对于我们开头的实例代码,最终生成的OPCODES是:

filename:    /home/huixinchen/foreach.php
function name: (null)
number of ops: 17
compiled vars: !0 = $arr, !1 = $key, !2 = $val
line   # op              fetch     ext return operands
-------------------------------------------------------------------------------
  2   0 SEND_VAL                         1
     1 SEND_VAL                         100
     2 DO_FCALL                   2     'range'
     3 ASSIGN                          !0, $0
  3   4 FE_RESET                     $2   !0, ->14
     5 FE_FETCH                     $3   $2, ->14
     6 ZEND_OP_DATA                   ~5
     7 ASSIGN                          !2, $3
     8 ASSIGN                          !1, ~5
  4   9 CONCAT                      ~7   !1, '-'
    10 CONCAT                      ~8   ~7, !2
    11 CONCAT                      ~9   ~8, '%0A'
    12 ECHO                           ~9
  5  13 JMP                           ->5
    14 SWITCH_FREE                       $2
  7  15 RETURN                          1
    16* ZEND_HANDLE_EXCEPTION
Copy after login

我们注意到FE_FETCH的op2的操作数是14,也就是JMP后一条opline,也就是说,在获取完最后一个数组元素以后,FE_FETCH失败的情况下,会跳到第14行opline,从而实现了循环的结束。
而15行opline的op1的操作数是指向了FE_FETCH,也就是无条件跳转到第5行opline,从而实现了循环。

附录:

void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC)
{
  zend_op *opline;
  zend_bool is_variable;
  zend_bool push_container = 0;
  zend_op dummy_opline;
 
  if (variable) {
     //是否是匿名数组
    if (zend_is_function_or_method_call(array)) {
        //是否是函数返回值
      is_variable = 0;
    } else {
      is_variable = 1;
    }
    /* 使用括号记录FE_RESET的opline行数 */
    open_brackets_token->u.opline_num = get_next_op_number(CG(active_op_array));
    zend_do_end_variable_parse(BP_VAR_W, 0 TSRMLS_CC); //获取数组/对象和zend_do_begin_variable_parse对应
    if (CG(active_op_array)->last > 0 &&
      CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) {
      /* Only lock the container if we are fetching from a real container and not $this */
      if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1.op_type == IS_VAR) {
        CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK;
        push_container = 1;
      }
    }
  } else {
    is_variable = 0;
    open_brackets_token->u.opline_num = get_next_op_number(CG(active_op_array));
  }
 
  foreach_token->u.opline_num = get_next_op_number(CG(active_op_array)); //记录数组Reset Opline number
 
  opline = get_next_op(CG(active_op_array) TSRMLS_CC); //生成Reset数组Opcode
 
  opline->opcode = ZEND_FE_RESET;
  opline->result.op_type = IS_VAR;
  opline->result.u.var = get_temporary_variable(CG(active_op_array));
  opline->op1 = *array;
  SET_UNUSED(opline->op2);
  opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0;
 
  dummy_opline.result = opline->result;
  if (push_container) {
    dummy_opline.op1 = CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1;
  } else {
    znode tmp;
 
    tmp.op_type = IS_UNUSED;
    dummy_opline.op1 = tmp;
  }
  zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); 
 
  as_token->u.opline_num = get_next_op_number(CG(active_op_array)); //记录循环起始点
 
  opline = get_next_op(CG(active_op_array) TSRMLS_CC);
  opline->opcode = ZEND_FE_FETCH;
  opline->result.op_type = IS_VAR;
  opline->result.u.var = get_temporary_variable(CG(active_op_array));
  opline->op1 = dummy_opline.result;  //被操作数组
  opline->extended_value = 0;
  SET_UNUSED(opline->op2);
 
  opline = get_next_op(CG(active_op_array) TSRMLS_CC);
  opline->opcode = ZEND_OP_DATA; //当使用key的时候附属操作数,当foreach中不包含key时忽略
  SET_UNUSED(opline->op1);
  SET_UNUSED(opline->op2);
  SET_UNUSED(opline->result);
}
void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC)
{
  zend_op *opline;
  znode dummy, value_node;
  zend_bool assign_by_ref=0;
 
  opline = &CG(active_op_array)->opcodes[as_token->u.opline_num]; //获取FE_FETCH Opline
  if (key->op_type != IS_UNUSED) {
    znode *tmp;//交换key和val
 
    tmp = key;
    key = value;
    value = tmp;
 
    opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; //表明需要同时获取key和val
  }
 
  if ((key->op_type != IS_UNUSED) && (key->u.EA.type & ZEND_PARSED_REFERENCE_VARIABLE)) {
     //key不能以引用方式获取
    zend_error(E_COMPILE_ERROR, "Key element cannot be a reference");
  }
 
  if (value->u.EA.type & ZEND_PARSED_REFERENCE_VARIABLE) {
     //以引用方式获取值
    assign_by_ref = 1;
    if (!(opline-1)->extended_value) {
        //根据FE_FETCH的上一条Opline也就是获取数组的扩展值来判断数组是否是匿名数组
      zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression");
    }
 
    opline->extended_value |= ZEND_FE_FETCH_BYREF; //指明按引用取
    CG(active_op_array)->opcodes[foreach_token->u.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; //重置原数组
  } else {
    zend_op *foreach_copy;
    zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.opline_num];
    zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.opline_num];
 
    /* Change "write context" into "read context" */
    fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */
    while (fetch != end) {
      --fetch;
      if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2.op_type == IS_UNUSED) {
        zend_error(E_COMPILE_ERROR, "Cannot use [] for reading");
      }
      fetch->opcode -= 3; /* FETCH_W -> FETCH_R */
    }
 
    /* prevent double SWITCH_FREE */
    zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy);
    foreach_copy->op1.op_type = IS_UNUSED;
  }
 
  value_node = opline->result; 
 
  if (assign_by_ref) {
    zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); //获取值(引用)
    zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC);//指明value node的type是IS_VAR
  } else {
    zend_do_assign(&dummy, value, &value_node TSRMLS_CC); //获取copy值
    zend_do_free(&dummy TSRMLS_CC);
  }
 
  if (key->op_type != IS_UNUSED) {
    znode key_node;
 
    opline = &CG(active_op_array)->opcodes[as_token->u.opline_num+1];
    opline->result.op_type = IS_TMP_VAR;
    opline->result.u.EA.type = 0;
    opline->result.u.opline_num = get_temporary_variable(CG(active_op_array));
    key_node = opline->result;
 
    zend_do_assign(&dummy, key, &key_node TSRMLS_CC);
    zend_do_free(&dummy TSRMLS_CC);
  }
 
  do_begin_loop(TSRMLS_C);
  INC_BPC(CG(active_op_array));
}
void zend_do_foreach_end(znode *foreach_token, znode *as_token TSRMLS_DC)
{
  zend_op *container_ptr;
  zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); //生成JMP opcode
 
  opline->opcode = ZEND_JMP;
  opline->op1.u.opline_num = as_token->u.opline_num; //设置JMP到FE_FETCH opline行
  SET_UNUSED(opline->op1);
  SET_UNUSED(opline->op2);
 
  CG(active_op_array)->opcodes[foreach_token->u.opline_num].op2.u.opline_num = get_next_op_number(CG(active_op_array)); //设置跳出循环的opline行
  CG(active_op_array)->opcodes[as_token->u.opline_num].op2.u.opline_num = get_next_op_number(CG(active_op_array)); //同上
 
  do_end_loop(as_token->u.opline_num, 1 TSRMLS_CC); //为循环嵌套而设置
 
  zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr);
  generate_free_foreach_copy(container_ptr TSRMLS_CC);
  zend_stack_del_top(&CG(foreach_copy_stack));
 
  DEC_BPC(CG(active_op_array)); //为PHP interactive模式而设置
}
Copy after login

同时还要注意的是,foreach在使用中是值还是传引用的问题。
php 中遍历一个array时可以使用for或foreach,foreach的语法为:foreach ($arr as $k => $v)。遍历数组,把index赋给$k,数组的值赋给$v,那么此处的赋值是传值还是传引用呢。先看下面的例子:

$arr = array(
  array('id' => 1, 'name' => 'name1'),
  array('id' => 2, 'name' => 'name2'),
);

foreach ($arr as $obj) {
  $obj['id'] = $obj['id'];
  $obj['name'] = $obj['name'] . '-modify';
}

print_r($arr); //输出的结果
Array(
  [0] => Array (
    [id] => 1
    [name] => name1
  )
  [1] => Array(
    [id] => 2
    [name] => name2
  )
)
Copy after login

观察可以发现在foreach循环中对$arr操作并没有影响到$arr的元素,所以这里的赋值是传值而不是传引用。那如果需要修改$arr中元素的值该怎么办呢?可以在变量前面加一个”&”符号,例如:

foreach ($arr as &$obj) {
  $obj['id'] = $obj['id'];
  $obj['name'] = $obj['name'] . '-modify';
}
Copy after login

再看另外一个例子,array里面存放的是object,

$arr = array(
  (object)(array('id' => 1, 'name' => 'name1')),
  (object)(array('id' => 2, 'name' => 'name2')),
);

foreach ($arr as $obj) {
  $obj->name = $obj->name . '-modify'; 
}

print_r($arr); //输出的结果

Array
(
  [0] => stdClass Object
    (
      [id] => 1
      [name] => name1-modify
    )

  [1] => stdClass Object
    (
      [id] => 2
      [name] => name2-modify
    )

)
Copy after login

此时可以看到原始数组中的object对象已经修改了,所以这里的赋值又是传引用而不是传值

综合上述,得出的结论:如果数组里面存放的是普通类型的元素就是采用传值的方式,存放对象类型元素采用的方式为传地址。

The above is the detailed content of In-depth understanding of the usage of foreach statement to loop arrays. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP returns an array with key values ​​flipped PHP returns an array with key values ​​flipped Mar 21, 2024 pm 02:10 PM

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values ​​in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values ​​swapped. $original_array=[

Lambda expression breaks out of loop Lambda expression breaks out of loop Feb 20, 2024 am 08:47 AM

Lambda expression breaks out of the loop, specific code examples are needed. In programming, the loop structure is an important syntax that is often used. However, in certain circumstances, we may want to break out of the entire loop when a certain condition is met within the loop body, rather than just terminating the current loop iteration. At this time, the characteristics of lambda expressions can help us achieve the goal of jumping out of the loop. Lambda expression is a way to declare an anonymous function, which can define simple function logic internally. It is different from an ordinary function declaration,

PHP returns all the values ​​in the array to form an array PHP returns all the values ​​in the array to form an array Mar 21, 2024 am 09:06 AM

This article will explain in detail how PHP returns all the values ​​of an array to form an array. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Using the array_values() function The array_values() function returns an array of all the values ​​in an array. It does not preserve the keys of the original array. $array=["foo"=>"bar","baz"=>"qux"];$values=array_values($array);//$values ​​will be ["bar","qux"]Using a loop can Use a loop to manually get all the values ​​of the array and add them to a new

Java Iterator vs. Iterable: A step into writing elegant code Java Iterator vs. Iterable: A step into writing elegant code Feb 19, 2024 pm 02:54 PM

Iterator interface The Iterator interface is an interface used to traverse collections. It provides several methods, including hasNext(), next() and remove(). The hasNext() method returns a Boolean value indicating whether there is a next element in the collection. The next() method returns the next element in the collection and removes it from the collection. The remove() method removes the current element from the collection. The following code example demonstrates how to use the Iterator interface to iterate over a collection: Listnames=Arrays.asList("John","Mary","Bob");Iterator

What are the alternatives to recursive calls in Java functions? What are the alternatives to recursive calls in Java functions? May 05, 2024 am 10:42 AM

Replacement of recursive calls in Java functions with iteration In Java, recursion is a powerful tool used to solve various problems. However, in some cases, using iteration may be a better option because it is more efficient and less prone to stack overflows. Here are the advantages of iteration: More efficient since it does not require the creation of a new stack frame for each recursive call. Stack overflows are less likely to occur because stack space usage is limited. Iterative methods as an alternative to recursive calls: There are several methods in Java to convert recursive functions into iterative functions. 1. Use the stack Using the stack is the easiest way to convert a recursive function into an iterative function. The stack is a last-in-first-out (LIFO) data structure, similar to a function call stack. publicintfa

A closer look at HTTP status code 100: What does it mean? A closer look at HTTP status code 100: What does it mean? Feb 20, 2024 pm 04:15 PM

A closer look at HTTP status code 100: What does it mean? The HTTP protocol is one of the most commonly used protocols in modern Internet applications. It defines the standard specifications required for communication between browsers and web servers. During the process of HTTP request and response, the server will return various types of status codes to the browser to reflect the processing of the request. Among them, HTTP status code 100 is a special status code used to indicate "continue". HTTP status codes consist of three digits, each status code has a specific meaning

PHP returns the current element in an array PHP returns the current element in an array Mar 21, 2024 pm 12:36 PM

This article will explain in detail about the current element in the array returned by PHP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. Get the current element in a PHP array PHP provides a variety of methods for accessing and manipulating arrays, including getting the current element in an array. The following introduces several commonly used techniques: 1. current() function The current() function returns the element currently pointed to by the internal pointer of the array. The pointer initially points to the first element of the array. Use the following syntax: $currentElement=current($array);2.key() function key() function returns the array internal pointer currently pointing to the element

In-depth understanding of how to use Linux pipelines In-depth understanding of how to use Linux pipelines Feb 21, 2024 am 09:57 AM

In-depth understanding of the use of Linux pipes In the Linux operating system, pipes are a very useful function that can use the output of one command as the input of another command, thereby conveniently realizing various complex data processing and operations. A deep understanding of how Linux pipes are used is very important for system administrators and developers. This article will introduce the basic concepts of pipelines and show how to use Linux pipelines for data processing and operations through specific code examples. 1. Basic concepts of pipes in Linux

See all articles