Home>

I want to modify so that the squared value of each value is reassigned after the value is output.

<? php
$nums_1 = [];
$nums_1 [] = 1;
$nums_1 [] = 2;
$nums_1 [] = 3;
foreach ($nums_1 as $key =>$num) {
    $num ** = 2;
    print ($num);
    echo "\ n";
}

Using $key
When the loop ends and the array is stored, I want the contents of the array to be squared.
I'm in trouble because I don't know how to write it.

foreach (array variable as $key =>variable) {
Processing I want to repeat
}

I intended to write it like this,
It doesn't work.
It would be very helpful if you could tell me.

I look forward to working with you.

  • Answer # 1

    If you wonder why the code works,

    I want to modify it so that it is reassigned

    is not it.

    foreachAfter the processing of
    $nums_1 // [1, 4, 9]
    I want you to become. If so,

    foreach ($nums_1 as $key =>$num) {
        $num ** = 2;
        print ($num);
        echo "\ n";
    + $nums_1 [$key] = $num;
    }

    How about adding?
    $numEven if you change$nums_1Does not change.
    This is not the case when passing by reference, but it is better not to use it basically, so for reference.

    Please refer to m.ts10806's answer for beautiful code.

  • Answer # 2

    $nums_1 [$key] = Information you want to assign;

    Or, if the values ​​are serial numbers, you can loop from range () and square them at the time of definition.

    $ar = [];
    foreach (range (1,3) as $n) {
        $ar [] = ($n) ** 2;
    }
    var_dump ($ar);