phparrayspass-by-referencephp-parse-error

Passing and using an array by reference in PHP


In a PHP function, I'd like to append values to an array that was passed in by reference. For example:

function foo(array &$arr) {
    $arr[] = "error on this line";
    $arr[] = "more";
    $arr[] = "stuff";
}

The error I get when I attempt to append something to the array is

PHP Parse error:  syntax error, unexpected ']', expecting T_STRING or T_VARIABLE or T_NUM_STRING in somefile.class.php on line xxx

I'm not sure I have the parameter defined correctly, or if this is even possible. Googling has so far not turned up any comparable examples.

EDIT: PHP Version 5.1.6.


Solution

  • I just ran your code and got the expected output, so I'm not sure what's happening. If arr wasn't an array, it wouldn't pass the typehint, so it's definitely an array.

    It's possible that you're running PHP < 5.4

    <?php
    
    function foo(array &$arr) {
        $arr[] = "error on this line";
        $arr[] = "more";
        $arr[] = "stuff";
    }
    
    $a = ["initial"];
    
    foo($a);
    
    var_dump($a);
    
    /*
    array(4) {
      [0] =>
      string(7) "initial"
      [1] =>
      string(18) "error on this line"
      [2] =>
      string(4) "more"
      [3] =>
      string(5) "stuff"
    }
    */
    

    For PHP < 5.4:

    <?php
    
    function foo(array &$arr) {
        array_push($arr, "error on this line");
        array_push($arr, "more");
        array_push($arr, "stuff");
    }
    
    $a = array("initial");
    
    foo($a);
    
    var_dump($a);
    
    /*
    array(4) {
      [0] =>
      string(7) "initial"
      [1] =>
      string(18) "error on this line"
      [2] =>
      string(4) "more"
      [3] =>
      string(5) "stuff"
    }
    */