Home > php教程 > php手册 > body text

php foreach 传值还是传引用

WBOY
Release: 2016-05-24 12:59:16
Original
1332 people have browsed it

php 中遍历一个array时可以使用for或foreach,foreach的语法为:foreach ($arr as $k => $v),遍历数组,把index赋给$k,数组的值赋给$v,那么此处的赋值是传值还是传引用呢.

php中foreach()的用法,代码如下:

foreach(array_name as $value) 
{ 
  statement; 
}
Copy after login

这里的array_name是你要遍历的数组名,每次循环中,array_name数组的当前元素的值被赋给$value,并且数组内部的下标向下移一步,也就是下次循环回得到下一个元素.

实例代码二:

foreach(array_name as $key => $value) 
{ 
   statement;  
}
Copy after login

这里跟第一种方法的区别就是多了个$key,也就是除了把当前元素的值赋给$value外,当前元素的键值也会在每次循环中被赋给变量$key,键值可以是下标值,也可以是字符串,比如book[0]=1中的"0",book[id]="001"中的"id".

看下面的例子,代码如下:

$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); //输出的结果
Copy after login

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对象已经修改了,所以这里的赋值又是传引用而不是传值.

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


本文地址:

转载随意,但请附上文章地址:-)

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template