Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

foreach

php

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

like image 531
user1179295 Avatar asked Mar 29 '12 07:03

user1179295


People also ask

How do I change the value of a forEach?

To change the value of all elements in an array: Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

Can the elements of an array be updated using a forEach loop?

forEach does not modify the array itself, the callback method can. The method returns undefined and cannot be chained like some other array methods. forEach only works on arrays, which means you need to be a little creative if you want to iterate over objects.

Can you change a forEach loop?

Why C#'s foreach loop cannot change what it loops over. With a foreach loop we easily iterate over all elements in a collection. During each pass through the loop, the loop variable is set to an element from a collection.

Does forEach pass reference?

This is an example why pass-by-reference in foreach loops is BAD. This is because when the second loop executes, $entry is still a reference. Thus, with each iteration the original reference is overwritten.


1 Answers

The $value variable in the array is temporary, it does not refer to the entry in the array.
If you want to change the original array entry, use a reference:

foreach ($store as $key => &$value) {
                       //  ^ reference
    $value .= '.txt.gz';
}
like image 200
deceze Avatar answered Sep 28 '22 11:09

deceze