PHP functions and arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • meekotherogue
    New Member
    • Jun 2010
    • 4

    #1

    PHP functions and arrays

    Just a quick question:
    Are arrays in php pass by reference?

    So if I had two functions:

    Code:
    function A($arr) { $arr[5]++; }
    
    function B() { 
    $arr = array();
    $arr[5] = 0;
    A($arr);
    echo "The new value is: ".$arr[5];
    }
    Should print:
    The new value is: 1;

    ??
    Last edited by Dormilich; Jun 5 '10, 09:50 AM. Reason: Please use [code] tags when posting code
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    No they are not pass by reference,

    The above code will out put: The new value is: 0

    Thanks for playing,

    Dan

    Comment

    • paulrajj
      New Member
      • Sep 2008
      • 47

      #3
      If u want to print the result as 1, then u should use pass by reference.

      Code:
      function A($arr) { $arr[5]++; }
       
      function B() { 
      $arr = array();
      $arr[5] = 0;
      A(&$arr);  // pass by reference
      echo "The new value is: ".$arr[5];
      }
      B();
      Hence the output will be 1.

      PHP References

      Comment

      Working...