Sasha Blazevic Sasha Blazevic - 1 year ago 127
PHP Question

Addition to values in a foreach-loop

So I have an array.

$numbers1 = [31, 60, 54, 7, 13, 2, 9, 68, 5, 2, 9, 68, 5, 2];




What I have to do is use a foreach-loop to sum each item with 20 and then place them in a new Array,
$newArray
. This is what I've come up with so far.

$numbers1 = [31, 60, 54, 7, 13, 2, 9, 68, 5, 2, 9, 68, 5, 2];

foreach ($numbers1 as &$value) {
$newArray = $value + 20;
}




But it doesn't seem to be working, as I receive the answer 22 instead of the array with the sum of the numbers. I know I have to echo it out, but I have to do that later in the exercise. I appreciate the help.

Answer Source

Your question basically works. Replace $newArray with $value as so:

$numbers1 = [31, 60, 54, 7, 13, 2, 9, 68, 5, 2, 9, 68, 5, 2];

foreach ($numbers1 as &$value) {
    $value += 20;
}

Then if you need it in a new array use add the following line afterwards:

$newArray = $numbers1;

Since you are passing $value by reference you can use the $value += 20 line.


If you don't want the pointless array reassignment you can do the following:

$numbers1 = [31, 60, 54, 7, 13, 2, 9, 68, 5, 2, 9, 68, 5, 2];

foreach ($numbers1 as value) {
    $newArray[] = $value + 20;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download