Skip to content
Advertisement

Why array is not updated when i want to print it out (print_r)?

<!DOCTYPE html>
<html>
<body>

<?php
    $array_task=array();
    fillArray($array_task);

     function fillArray($array){
        $array1=array();
        $array2=array();
        for ($i=0;$i<8;$i++){
            $array1[$i]=$i+1;
            $array2[$i]=rand(0,100);
        }
        $array=array_combine($array1,$array2);
        echo"Array before any editions <br>";
        print_r($array);
        echo"<br>Array after adding sum and multiplication <br>";
        addSumMulti($array);
        print_r($array);
        echo"<br>Array after adding last element after each array element <br>";
        #addAfterEach($array);
    }
    
        
    function addSumMulti($array){
        $sum=0;
        $multiplication=1;
        for ($i=1;$i<=10;$i++){
            $sum+=$array[$i];
            if ($i==3 || $i==4){
                $multiplication*=$array[$i];
            }
        }
        $array[9]=$sum;
        $array[10]=$multiplication;   
        print_r($array);
        echo "<br>";
    }
    
?>

</body>
</html>

first print_r ($array) shows 8elements, then in the next function i add 2 elements. And print_r in the function addSumMulti shows 10 elements, but print_r after function addSumMulti inside the fillArray shows only 8 elements. What is wrong, what should I change so that i could see 10 elements in print_r after addSumMulti (21 line)?

Advertisement

Answer

In PHP ordinary variables are passed by value*. So, when you pass your array to your function a new copy is made which your function code manipulates. Your function doesn’t return any values, so the new values of your array are lost, and the calling code sees only the original copy of the array.

There are two ways to make the changes to the original array:

  • return a value from the function. e.g.:
    function addLine($arr) {
        $arr[] = "Additional Line";
        return $arr
    }
    $arr = ["First line"];
    $arr = addLine($arr);
  • or pass in the variable by reference. E.g:
    function addLine(&$arr) {
        $arr[] = "Additional Line";
        return $arr
    }
    $arr = ["First line"];
    addLine($arr);

See Variable scope and Passing By Reference

*Objects are always passed by reference

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement