Info
Open the page on your phone

Variables in PHP: Pass by Value or by Reference

Variables in PHP can be passed by value or by reference. It depends on the data type of the variable and how it is passed to a function.

Pass by value:

Simple data types:

  • Integers (int)
  • Floating-point numbers (float)
  • Strings (string)
  • Boolean values (bool)
  • Copies created:

  • When variables of these types are passed to a function, copies of their values are created.
  • Changes made to the copies inside the function do not affect the original variables.
  • Pass by reference:

    Complex data types:

  • Arrays (array)
  • Objects (object)
  • Reference to the original:

  • When variables of these types are passed to a function, a reference to the original variable is passed, not a copy.
  • Changes made to the variable inside the function also change the value of the original variable.
  • How to determine how a variable is passed:

    Ampersand symbol (&):

  • Before the variable name in the function parameter: pass by reference.
  • Example: function 'foo(&$bar) { ... }'
  • Absence of the & symbol:

  • Pass by value.
  • Example: function 'foo($bar) { ... }'