更改foreach循环内的值不会更改正在迭代的数组中的值

编程入门 行业动态 更新时间:2024-10-26 16:34:00
本文介绍了更改foreach循环内的值不会更改正在迭代的数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 为什么这会产生这种结果: $ 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/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 php/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循环内的值不会更改正在迭代的数组中的值

本文发布于:2023-10-25 22:27:17,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   迭代   foreach

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!