How to pass an array into a function, and return the results with an array

后端 未结 9 1551
你的背包
你的背包 2021-02-05 07:25

So I\'m trying to learn how to pass arrays through a function, so that I can get around PHP\'s inability to return multiple values. Haven\'t been able to get anything to work so

9条回答
  •  我寻月下人不归
    2021-02-05 07:56

    You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)

    function foo(&$arr) { # note the &
      $arr[3] = $arr[0]+$arr[1]+$arr[2];
    }
    $waffles = array(1,2,3);
    foo($waffles);
    echo $waffles[3]; # prints 6
    

    That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?

提交回复
热议问题