Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

php - Changing value inside foreach loop doesn't change value in the array being iterated over

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...