Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach change array value

Tags:

foreach

php

When you have a foreach loop like below, I know that you can change the current element of the array through $array[$key], but is there also a way to just change it through $value?

foreach($array as $key => $value){

}

It's probably really simple, but I'm quite new to PHP so please don't be annoyed by my question :)

like image 358
fckye Avatar asked Sep 14 '14 17:09

fckye


People also ask

What is array foreach in PHP?

PHP Array foreach is a construct in PHP that allows to iterate over arrays easily. In this tutorial, we will learn the syntax of foreach loop construct and go through following scenarios

How to iterate over array of numbers in PHP?

PHP Array foreach is a construct in PHP that allows to iterate over arrays easily. In this tutorial, we will learn the syntax of foreach loop construct and go through following scenarios foreach loop to iterate over PHP array of numbers.

Can you modify an array in a foreach loop?

Note that foreach does not modify the internal array pointer, which is used by functions such as current () and key () . It is possible to customize object iteration . 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 .

How to modify an array inside a loop in PHP 7?

As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. In PHP 7, foreach does not use the internal array pointer. 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.


Video Answer


1 Answers

To be able to directly assign values to $value, you want to reference $value by preceding it with & like this:

foreach($array as $key => &$value){
    $value = 12321; //the same as $array[$key] = 12321;
}

unset($value);

After the foreach loop, you should do unset($value) because you're still able to access it after the loop.
Note: You can only pass $value by reference when the array is a variable. The following example won't work:

foreach(array(1, 2, 3) as $key => &$value){
    $value = 12321; //the same as $array[$key] = 12321
}

unset($value);


The php manual on foreach loops

like image 60
Jonan Avatar answered Oct 25 '22 09:10

Jonan