更改foreach循环内的值不会更改正在迭代的数组中的值 [英] Changing value inside foreach loop doesn't change value in the array being iterated over
问题描述
$ foreach($ store as $ key => $ value){
$ value = $ value。。txt.gz;
}
unset($ value);
print_r($ store);
Array
(
[1] => 101Phones - 产品目录TXT
[2] => 1-800-FLORALS - 产品目录1
$ b $ p
$ b
我试图获得101个电话 - 产品目录TXT.txt.gz
有什么想法吗?
编辑:好吧我找到了解决方案...我的数组中的变量有值不能看到...正在做
$ b $ $ $ $ $ $ $ $ $ $输出= preg_replace('/ [^(\x20-\x7F) ] * /','',$ output);
echo($ output);
清理并使其正常工作
doc http:// php.net/manual/en/control-structures.foreach.php 清楚地说明了为什么你有一个问题:
为了能够直接修改循环中的数组元素在$ value之前用& ;.在这种情况下,值将由引用赋值。
<< ;?php
$ arr = array(1,2,3,4);
foreach($ arr as& $ value){
$ value = $ value * 2;
// $ arr现在是数组(2,4,6,8)
unset($ value); //用最后一个元素
?>来分隔引用。
引用$ value是唯一可能的,如果迭代数组可以被引用(即,如果它是一个变量) 。以下代码将无效:
<?php
/ **这不起作用/
foreach(array(1,2,3,4)为& $ value){
$ value = $ value * 2;
}
?>
Why does this yield this:
foreach( $store as $key => $value){
$value = $value.".txt.gz";
}
unset($value);
print_r ($store);
Array
(
[1] => 101Phones - Product Catalog TXT
[2] => 1-800-FLORALS - Product Catalog 1
)
I am trying to get 101Phones - Product Catalog TXT.txt.gz
Thoughts on whats going on?
EDIT: Alright I found the solution...my variables in my array had values I couldn't see...doing
$output = preg_replace('/[^(\x20-\x7F)]*/','', $output);
echo($output);
Cleaned it up and made it work properly
The doc http://php.net/manual/en/control-structures.foreach.php clearly states why you have a problem:
"In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference."
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:
<?php
/** this won't work **/
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>
这篇关于更改foreach循环内的值不会更改正在迭代的数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!