Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...