• Language Reference

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Note : For our purposes here, a letter is a-z, A-Z, and the bytes from 128 through 255 ( 0x80-0xff ).
Note : $this is a special variable that can't be assigned. Prior to PHP 7.1.0, indirect assignment (e.g. by using variable variables ) was possible.

See also the Userland Naming Guide .

For information on variable related functions, see the Variable Functions Reference .

<?php $var = 'Bob' ; $Var = 'Joe' ; echo " $var , $Var " ; // outputs "Bob, Joe" $ 4site = 'not yet' ; // invalid; starts with a number $_4site = 'not yet' ; // valid; starts with an underscore $täyte = 'mansikka' ; // valid; 'ä' is (Extended) ASCII 228. ?>

By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions .

PHP also offers another way to assign values to variables: assign by reference . This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs ' My name is Bob ' twice: <?php $foo = 'Bob' ; // Assign the value 'Bob' to $foo $bar = & $foo ; // Reference $foo via $bar. $bar = "My name is $bar " ; // Alter $bar... echo $bar ; echo $foo ; // $foo is altered too. ?>

One important thing to note is that only named variables may be assigned by reference. <?php $foo = 25 ; $bar = & $foo ; // This is a valid assignment. $bar = &( 24 * 7 ); // Invalid; references an unnamed expression. function test () { return 25 ; } $bar = & test (); // Invalid. ?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to false , integers and floats default to zero, strings (e.g. used in echo ) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. E_WARNING (prior to PHP 8.0.0, E_NOTICE ) level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Improve This Page

User contributed notes 2 notes.

To Top

CodedTag

  • Assignment Operators

PHP assignment operators enable you to frequently engage in performing calculations and operations on variables, requiring the assignment of results to other variables. Consequently, this is precisely where assignment operators prove indispensable, allowing you to seamlessly execute an operation and assign the result to a variable within a single statement.

In the following sections, we’ll delve into the different types of PHP assignment operators and explore how to use them.

Table of Contents

Php arithmetic assignment operators, php bitwise assignment operators.

  • Null Coalescing Operator

Assigning a Reference to a PHP Variable

Other assignment operators, wrapping up.

The most commonly used assignment operator in PHP is the equals sign (=). For instance, in the following code, the value 10 is assigned to the variable $x:

Now, let’s explore each type with examples:

Numeric data undergoes mathematical operations through the utilization of arithmetic operators. In PHP, this is where arithmetic assignment operators come into play, employed to perform these operations. The arithmetic assignment operators include:

  • += or $x + $y (Addition Assignment Operator)
  • -= or $x - $y (Subtraction Assignment Operator)
  • *= or $x * $y (Multiplication Assignment Operator)
  • /= or $x / $y (Division Assignment Operator)
  • %= or $x % $y (Modulus Assignment Operator)
  • **= or $x ** $y (Exponentiation Assignment Operator)

Consider the following example:

In this example, the addition assignment operator increases the value of $x by 5, and then assigns the result back to $x, producing an output of 15.

You can leverage these arithmetic assignment operators to perform complex calculations in a single statement, making your code more concise and easier to read. For more details, refer to this tutorial .

One crucial aspect of computer science involves the manipulation of binary bits in PHP. Let’s delve into one of the more complex assignment operators—specifically, the PHP bitwise operators.

Developers use bitwise operators to manipulate data at the bit level. PHP bitwise assignment operators perform bitwise operations. Here are the bitwise assignment operators:

  • &= or $x & $y (Bitwise AND Assignment Operator)
  • |= or $x | $y (Bitwise OR Assignment Operator)
  • ^= or $x ^ $y (Bitwise XOR Assignment Operator)
  • ~= or $x ~ $y (Bitwise NOT Assignment Operator)
  • <<= or $x << $y (Left Shift Assignment Operator)
  • >>= or $x >> $y (Right Shift Assignment Operator)

Let’s illustrate with an example:

In this example, a bitwise OR operation is performed between the values of $x and 2 using the bitwise OR assignment operator. The result is then assigned to $x, yielding an output of 7.

Here is a full explanation along with more examples of bitwise operators .

Let’s move to the section below to understand the Null Coalescing Operator in PHP.

Furthermore, developers use the null coalescing operator to assign a default value to a variable if it is null. The double question mark (??) symbolizes the null coalescing operator. Consider the following example:

In this example, the null coalescing operator is used to assign the value ‘John Doe’ to the variable $fullName. If $name is null, the value ‘John Doe’ will be assigned to $fullName.

The null coalescing operator simplifies code by enabling the assignment of default values to variables. By reading this tutorial , you will gain more information about it

Anyway, assigning a reference in PHP is one of the language’s benefits, enabling developers to set a value and refer back to it anywhere during the script-writing process. Let’s move to the section below to take a closer look at this concept.

Furthermore, individuals use the reference assignment operator =& to assign a reference to a variable rather than copying the value of the variable. Consider the following example:

In this example, a reference to the variable $x is created using the reference assignment operator. The value 10 is then assigned to $x, and the output displays the value of $y. Since $y is a reference to $x, it also changes to 10, resulting in an output of 10.

The reference assignment operator proves useful when working with large data sets, enabling you to avoid copying large amounts of data.

Let’s explore some other assignment operators in the paragraphs below.

In addition to the arithmetic, bitwise, null coalescing, and reference assignment operators, PHP provides other assignment operators for specific use cases. These operators are:

  • .= (Concatenation Assignment Operator)
  • ??= (Null Coalescing Assignment Operator)

Now, let’s explore each of these operators in turn:

Concatenation Assignment Operator: Used to concatenate a string onto the end of another string. For example:

In this example, the concatenation assignment operator appends the value of $string2 to the end of $string1, resulting in the output “Hello World!”.

The Null Coalescing Assignment Operator is employed to assign a default value to a variable when it is detected as null. For example:

In this example, the null coalescing assignment operator assigns the value ‘John Doe’ to the variable $name. If $name is null, the value ‘John Doe’ will be assigned to $name.

Let’s summarize it.

we’ve taken a comprehensive look at the different types of PHP assignment operators and how to use them. Assignment operators are essential tools for any PHP developer, facilitating calculations and operations on variables while assigning results to other variables in a single statement.

Moreover, leveraging assignment operators allows you to make your code more concise, easier to read, and helps in avoiding common programming errors.

Did you find this article helpful?

 width=

Sorry about that. How can we improve it ?

  • Facebook -->
  • Twitter -->
  • Linked In -->
  • Install PHP
  • Hello World
  • PHP Constant
  • PHP Comments

PHP Functions

  • Parameters and Arguments
  • Anonymous Functions
  • Variable Function
  • Arrow Functions
  • Variadic Functions
  • Named Arguments
  • Callable Vs Callback
  • Variable Scope

Control Structures

  • If-else Block
  • Break Statement

PHP Operators

  • Operator Precedence
  • PHP Arithmetic Operators
  • PHP Bitwise Operators
  • PHP Comparison Operators
  • PHP Increment and Decrement Operator
  • PHP Logical Operators
  • PHP String Operators
  • Array Operators
  • Conditional Operators
  • Ternary Operator
  • PHP Enumerable
  • PHP NOT Operator
  • PHP OR Operator
  • PHP Spaceship Operator
  • AND Operator
  • Exclusive OR
  • Spread Operator

Data Format and Types

  • PHP Data Types
  • PHP Type Juggling
  • PHP Type Casting
  • PHP strict_types
  • Type Hinting
  • PHP Boolean Type
  • PHP Iterable
  • PHP Resource
  • Associative Arrays
  • Multidimensional Array

String and Patterns

  • Remove the Last Char
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

PHP References: How They Work, and When to Use Them

19 November 2010 / 18 Comments

PHP References: How They Work, and When to Use Them

References are a very useful part of PHP and, for that matter, most other programming languages. However, references can be somewhat confusing when you first start learning about them.

This tutorial is a gentle introduction to references in PHP. You find out what references are, and how they work. You learn how to create and delete references, as well as pass references to and from functions. You also explore some other uses of references, and discover situations where PHP creates references automatically on your behalf.

What exactly is a reference, anyway?

A reference is simply a way to refer to the contents of a variable using a different name. In many ways, references are like file shortcuts in Windows, file aliases in Mac OS X, and symbolic links in Linux.

  • Assigning by reference

An easy way to create a reference is known as assigning by reference . Consider the following simple example:

Here we’ve created a variable, $myVar , and given it a value of “Hi there”. Then we’ve assigned that value to another variable, $anotherVar . This copies the value from the first variable to the second.

We then changed the value stored in $anotherVar to “See you later”. Since the 2 variables are independent, $myVar still keeps its original value (“Hi there”), which we then display in the page. So far, so good.

Now, let’s change the above example to assign $myVar to $anotherVar by reference , rather than by value. To do this, we simply put an ampersand ( & ) after the equals sign:

Now you can see that $myVar ‘s value has also changed to “See you later”! What’s going on here?

Rather than assigning the value of $myVar to $anotherVar — which simply creates 2 independent copies of the same value — we’ve made $anotherVar a reference to the value that $myVar refers to. In other words, $myVar and $anotherVar now both point to the same value. So when we assign a new value to $anotherVar , the value of $myVar also changes.

Note that we could have changed the value of $myVar to “See you later” instead of changing $anotherVar , and the result would have been exactly the same. The 2 variables are, in effect, identical.

Removing a reference

You delete a reference using the unset() function, in the same way that you delete a regular variable.

When you unset a reference, you’re merely removing that reference, not the value that it references:

The value remains in memory until you unset all references to it, including the original variable:

Passing references to functions

Handshake

References really come into their own when you start passing them as arguments to functions. Normally, when you pass a variable to a function, the function receives a copy of that variable’s value. By passing a reference to a variable, however, the function can refer to — and, more importantly, modify — the original variable.

To pass an argument by reference, you place an ampersand before the parameter name when you define the function:

Now, whenever you call myFunc() and pass a variable to it, PHP passes a reference to the variable, rather than the variable’s value.

Let’s look at a simple example of passing by reference:

Here we created a function, goodbye() , that accepts a reference to a variable. The reference is stored in the parameter $greeting . The function assigns a new value (“See you later”) to $greeting , which changes the value stored in the variable that was passed to the function.

We test this out by creating a variable, $myVar , with an initial value of “Hi there”, and calling goodbye() , passing $myVar by reference. goodbye() then changes the value stored in $myVar to “See you later”.

So, use pass-by-reference whenever you want a function to change a variable that’s passed to it. Simple!

By the way, don’t be tempted to put an ampersand before the argument name in your function call:

The ampersand before the parameter in the function definition is sufficient to pass the variable by reference.

Many built-in PHP functions use pass-by-reference. For example, the sort() function accepts a reference to the array to sort, so that it can change the order of the elements in the array.

Returning references from functions

As well as passing references to functions, you can return references from functions. To do this, place an ampersand before the function name when you define the function. You should also use assign-by-reference ( =& ) when assigning the returned reference to a variable, otherwise you’ll merely assign the value, not the reference. Here’s an example:

In this example, our getNumWidgets() function retrieves the global variable $numWidgets and returns a reference to it. We then call getNumWidgets() , store the returned reference in $numWidgetsRef , and decrement the value that $numWidgetsRef points to. This is the same value that is pointed to by $numWidgets , as you can see by the results of the echo statements.

You probably won’t use return-by-reference as often as pass-by-reference, but it can be useful in certain situations, such as when you want to write a finder function (or class method) that finds a variable (or class property) and returns a reference to the variable or property, so that the calling code can then manipulate the variable or property.

Using references to change values in foreach loops

Roulette wheel

Another handy use of references is to change values in an array when using a foreach loop. With a regular foreach loop, you’re working with copies of the array values, so if you change a value you’re not affecting the original array. For example, let’s try to change an array of band names to uppercase with a foreach loop:

The above example displays:

As you can see, the original array has not been changed by the foreach loop. However, if we place an ampersand before $band in the foreach statement then $band becomes a reference to the original array element, rather than a copy. We can then convert the array elements to uppercase:

Our code now runs as intended, producing this:

Another way to change array values in a loop is to use a for loop instead of foreach .

When references are used automatically

Robot

So far you’ve looked at 4 ways to create references explicitly:

  • Passing by reference
  • Returning by reference
  • Creating a reference in a foreach loop

In addition, there are occasions when PHP automatically creates references for you. Most of the time you won’t care, but it can be useful to know this stuff!

When using the global keyword

When you use global to access a global variable within a function, you are in fact creating a reference to the global variable in the $GLOBALS array. So:

does the same thing as:

When using $this

When you use the $this keyword within an object’s method to refer to the object, then it’s worth remembering that $this is always a reference to the object, rather than a copy of it. For example:

Since $this is a reference to the object in the above example, the method is able to change a property within the object to a new value.

When passing objects around

Unlike other types of variable, whenever you assign, pass, or return an object, you’re passing a reference to the object, not a copy. This is usually what you want to happen, since the function or method you pass an object to usually needs to work on the actual object, not a copy of it. For example:

In the few situations when you do actually want to make a copy of an object, you can use the clone keyword.

In fact, things are a bit more subtle than this. When you create an object variable, that variable merely contains a pointer to the object in memory, not the object itself. When you assign or pass that variable, you do in fact create a copy of the variable. But the copy is also merely a pointer to the object — both copies still point to the same object. Therefore, for most intents and purposes, you’ve created a reference.

In this tutorial you’ve learned the fundamentals of variable references in PHP. You’ve explored assigning, passing, and returning variables by reference; learned how to use references to change array elements in a foreach loop; and looked at situations where PHP creates references for you automatically.

If you’d like to learn more, check out the References Explained section of the PHP website. Have fun! 🙂

Reader Interactions

' src=

4 December 2010 at 2:41 pm

Thanks, Brilliant tutorial, Very well explained.

' src=

6 December 2010 at 9:31 pm

@akk: Thanks for the feedback – I’m glad you found the tutorial helpful. 🙂 References can be a tricky topic!

' src=

14 October 2011 at 11:15 am

A great learning web forum ever I came across.

' src=

11 October 2013 at 6:01 am

Excellent! Thanks for showing real use examples.

' src=

29 October 2016 at 5:59 am

Thank you man for this great effort, this tutorial explains the topic easily and professionally.

' src=

25 April 2019 at 1:10 pm

thanks that is very comlete

' src=

18 May 2019 at 4:34 am

Thank you, Matt!! I have needed a clear explanation of this, and here it is 🙂

' src=

22 May 2019 at 11:50 pm

You’re welcome Erin, glad it helped 🙂

' src=

14 September 2019 at 7:04 pm

Thank you very much, only after your tutorial I understood the “References” topic. Had a hard time with it before. Thank you, best wishes!

17 September 2019 at 8:45 am

You’re welcome 🙂

' src=

27 June 2020 at 3:33 pm

Thanks for this article, with examples very easy to understand. Helpful to understand the references, that can be a little abstract.

1 July 2020 at 12:08 am

You’re welcome, Joseph 🙂

' src=

19 July 2020 at 4:55 am

Thank you very much for this useful explanation, Matt.

One thing that I did note was that for me, your &getNumWidgets() example of the use of a global variable did not work in my WordPress site–specifically in my Enfold theme. I had to declare the $numWidgets variable as global outside the function for the function’s reference to it to work:

I’ve seen other posts elsewhere talk about how you have to do this with some plugins.

Thanks again!

29 July 2020 at 4:25 am

Thanks for your reply Gary! Yes, that’s probably because your code is being called from inside another function in the Enfold theme, and therefore you need to declare that variable as global in that scope also.

' src=

18 November 2020 at 9:50 am

Thank you Matt!

You explained very clearly so that even a junior level programmer can easily understand the concept of references and avoid the confusions.

18 November 2020 at 10:11 am

Thanks Ahmed ?

' src=

30 April 2021 at 12:40 am

thank you so much for this great explanation !

' src=

16 January 2023 at 7:20 pm

outstanding explainer, thanks!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Contact Matt

  • Call Me: +61 2 8006 0622

Follow Matt

Copyright © 1996-2024 Elated Communications. All rights reserved. Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits

  • PHP Tutorial
  • PHP Exercises
  • PHP Calendar
  • PHP Filesystem
  • PHP Programs

PHP Array Programs

Php string programs.

  • PHP Interview Questions
  • PHP IntlChar
  • PHP Image Processing
  • PHP Formatter
  • Web Technology

PHP Basic Programs

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • How to detect search engine bots with PHP ?
  • How to set PHP development environment in windows ?
  • How to turn off PHP Notices ?
  • What does '<?=' short open tag mean in PHP ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • PHP | Print the last value of an array without affecting the pointer
  • How to merge the first index of an array with the first index of second array?
  • How to create a string by joining the array elements using PHP ?
  • How to sort an Array of Associative Arrays by Value of a Given Key in PHP ?
  • How to make a leaderboard using PHP ?
  • How to check an array is multidimensional or not in PHP ?
  • Multidimensional Associative Array in PHP
  • How to merge the duplicate value in multidimensional array in PHP ?
  • Convert multidimensional array to XML file in PHP
  • How to search by multiple key => value in PHP array ?
  • How to search by key=>value in a multidimensional array in PHP ?
  • PHP program to find the Standard Deviation of an array
  • PHP program to check for Anagram

PHP Function Programs

How to pass php variables by reference .

  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • Build a Grocery Store Web App using PHP with MySQL
  • How to delete text from file using preg_replace() function in PHP ?

PHP Date Programs

  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to prepend a string in PHP ?
  • How to replace a word inside a string in PHP ?
  • How to remove all white spaces from a string in PHP ?
  • How to count the number of words in a string in PHP ?
  • How to find number of characters in a string in PHP ?
  • How to get a substring between two strings in PHP?
  • How to get a variable name as a string in PHP?
  • Removing occurrences of a specific character from end of a string in PHP
  • How to convert string to boolean in PHP?
  • Generating Random String Using PHP
  • How to generate a random, unique, alphanumeric string in PHP
  • Remove new lines from string in PHP
  • Insert string at specified position in PHP
  • PHP | Program to check a string is a rotation of another string

PHP Classes Programs

  • PHP | Access Specifiers
  • PHP | Constructors and Destructors
  • PHP | Type Casting and Conversion of an Object to an Object of other class
  • How to merge two PHP objects?
  • Abstract Classes in PHP

PHP JSON Programs

  • How to parse a JSON File in PHP ?
  • How to generate Json File in PHP ?
  • How to Convert JSON file into CSV in PHP ?
  • How to Convert XML data into JSON using PHP ?
  • How to Insert JSON data into MySQL database using PHP ?
  • How to convert PHP array to JavaScript or JSON ?
  • How to receive JSON POST with PHP ?
  • How to use cURL to Get JSON Data and Decode JSON Data in PHP ?

PHP File Systems Programs

  • How to Create a Folder if It Doesn't Exist in PHP ?
  • How to check if File Exists in PHP ?
  • How to write Into a File in PHP ?
  • Deleting all files from a folder using PHP
  • How to get file name from a path in PHP ?
  • How to log errors and warnings into a file in php?
  • How to extract extension from a filename using PHP ?
  • How to get names of all the subfolders and files present in a directory using PHP?

By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn’t have any effect on either of the variables.

Pass by reference: When variables are passed by reference, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ). Scope of both global and function variable becomes global as both variables are defined by same reference. Therefore, whenever global variable is change, variable inside function also gets changed and vice-versa is applicable.

Please Login to comment...

Similar reads.

  • PHP-function
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Getting started with PHP
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • Alternative Syntax for Control Structures
  • Array iteration
  • Asynchronous programming
  • Autoloading Primer
  • BC Math (Binary Calculator)
  • Classes and Objects
  • Coding Conventions
  • Command Line Interface (CLI)
  • Common Errors
  • Compilation of Errors and Warnings
  • Compile PHP Extensions
  • Composer Dependency Manager
  • Contributing to the PHP Core
  • Contributing to the PHP Manual
  • Control Structures
  • Create PDF files in PHP
  • Cryptography
  • Datetime Class
  • Dependency Injection
  • Design Patterns
  • Docker deployment
  • Exception Handling and Error Reporting
  • Executing Upon an Array
  • File handling
  • Filters & Filter Functions
  • Functional Programming
  • Headers Manipulation
  • How to break down an URL
  • How to Detect Client IP Address
  • HTTP Authentication
  • Image Processing with GD
  • Installing a PHP environment on Windows
  • Installing on Linux/Unix Environments
  • Localization
  • Machine learning
  • Magic Constants
  • Magic Methods
  • Manipulating an Array
  • Multi Threading Extension
  • Multiprocessing
  • Object Serialization
  • Output Buffering
  • Outputting the Value of a Variable
  • Parsing HTML
  • Password Hashing Functions
  • Performance
  • PHP Built in server
  • php mysqli affected rows returns 0 when it should return a positive integer
  • Processing Multiple Arrays Together
  • Reading Request Data
  • Assign by Reference
  • Pass by Reference
  • Return by Reference
  • Regular Expressions (regexp/PCRE)
  • Secure Remeber Me
  • Sending Email
  • Serialization
  • SOAP Client
  • SOAP Server
  • SPL data structures
  • String formatting
  • String Parsing
  • Superglobal Variables PHP
  • Type hinting
  • Type juggling and Non-Strict Comparison Issues
  • Unicode Support in PHP
  • Unit Testing
  • Using cURL in PHP
  • Using MongoDB
  • Using Redis with PHP
  • Using SQLSRV
  • Variable Scope
  • Working with Dates and Time
  • YAML in PHP

PHP References Assign by Reference

Fastest entity framework extensions.

This is the first phase of referencing. Essentially when you assign by reference , you're allowing two variables to share the same value as such.

$foo and $bar are equal here. They do not point to one another. They point to the same place ( the "value" ).

You can also assign by reference within the array() language construct. While not strictly being an assignment by reference.

Note , however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value.

Assigning by reference is not only limited to variables and arrays, they are also present for functions and all "pass-by-reference" associations.

Assignment is key within the function definition as above. You can not pass an expression by reference, only a value/variable. Hence the instantiation of $a in bar() .

Got any PHP Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

  • Variable Assignment, Expressions, and Operators

Variables are containers for storing information, such as numbers or text so that they can be used multiple times in the code. Variables in PHP are identified by a dollar sign ($) followed by the variable name. A variable name must begin with a letter or the underscore character and only contain alphanumeric characters and underscores. A variable name cannot contain spaces. Finally, variable names in PHP are case-sensitive.

  • Post author By BrainBell
  • Post date May 12, 2022

php assign by reference

This tutorial covers the following topics:

  • Define a variable
  • Assign a variable by reference
  • Assign a string value to a variable

Assignment Operators

  • Arithmetic Operators (See Comparison Operators and Logical Operators on Conditional Expression Tutorial).

Operator precedence

Expressions, define a variable.

PHP uses the  =  symbol as an assignment operator. The variable goes on the left of the equal sign, and the value goes on the right. Because it assigns a value, the equal sign is called the  assignment operator .

$ variableName = 'Assigned Value' ;

You can break the above example into the following parts:

  • A dollar sign $ prefix
  • Variable name
  • The assignment operator (equal sign = )
  • Assigned value
  • Semicolon to terminate the statement

A PHP variable must be defined before it can be used. Attempting to use an undefined variable will trigger an error exception:

In PHP, you do not need to declare a variable separately before using it. Just assign value to a variable by using the assignment operator (equals sign = ) to make it defined or initialized:

A defined variable can be used by referencing its name, for example, use the print or echo command (followed by the variable’s name) to display the value of the variable on the web page:

Variable names are case-sensitive in PHP, so  $Variable , $variable , $VAriable , and $VARIABLE are all different variables.

Text requires quotes

If you look closely at the PHP code block in the above example, you’ll notice that the value assigned to the second variable isn’t enclosed in quotes. It looks like this:

Then the ‘BrainBell.com’ did use quotes, like this:

The simple rules are as follows:

  • The text requires quotes (single or double)
  • No quotes are required for numbers,  True ,  False  and  Null

Assign a string value to a variable:

Concatenate two strings together to produce “test string”:

Add a string to the end of another to produce “test string”:

Here is a shortcut to adding a string to the end of another:

Assign by reference

By default, PHP assigns all variables other than objects by value and not by reference. PHP has optimizations to make assignment by value faster than assigning by reference, but if you want to assign by reference you can use the  &  operator as follows:

The assignment operator (equal = ) can be combined with other operators to make it easier to write certain expressions. See the following table:

These operators assign values to variables. They start with the assignment operator = and move on to += , -= , etc.(see above table). The operator += adds the value on the right side to the variable on the left:

Arithmetic Operators

Using an operator, you can manipulate the contents of one or more variables or constants to produce a new value. For example, this code uses the addition operator (  +  ) to add the values of  $x  and  $y  together to produce a new value:

So an operator is a symbol that manipulates one or more values, usually producing a new value in the process. The following list describes the types of arithmetic operators:

Sum integers to produce an integer:

The values and variables that are used with an operator are known as operands.

Subtraction, multiplication, and division might have a result that is a float or an integer, depending on the initial value of $var :

Multiply to double a value:

Halve a value:

These work with float types too:

Get the remainder of dividing 5 by 4:

4 exponent (or power) of 2:

These all add 1 to $var:

And these all subtract 1 from $var:

If the  --  or  ++  operator appears before the variable then the interpreter will first evaluate it and then return the changed variable:

If the  --  or  ++  operator appears after the variable then the interpreter will return the variable as it was before the statement run and then increment the variable:

There are many mathematical functions available in the math library of PHP for more complex tasks. We introduce some of these in the next pages.

The precedence of operators in an expression is similar to the precedence defined in any other language. Multiplication and division occur before subtraction and addition, and so on. However, reliance on evaluation orders leads to unreadable, confusing code. Rather than memorize the rules, we recommend you construct unambiguous expressions with parentheses because parentheses have the highest precedence in evaluation.

For example, in the following fragment  $variable  is assigned a value of 32 because of the precedence of multiplication over addition:

The result is much clearer if parentheses are used:

But the following example displays a different result because parentheses have the highest precedence in evaluation.

An expression in PHP is anything that evaluates a value; it is a combination of values, variables, operators, and functions that results in a value. Here are some examples of expressions:

An expression has a value and a type; for example, the expression  4 + 7  has the value  11  and the type  integer,  and the expression "abcdef" has the value  abcdef  and the type  string . PHP automatically converts types when combining values in an expression. For example, the expression 4 + 7.0 contains an integer and a float; in this case, PHP considers the integer as a floating-point number, and the result is a float. The  type conversions  are largely straightforward; however, there are some traps, which are discussed later in this section.

Getting Started with PHP:

  • Introducing PHP
  • PHP Development Environment
  • Delimiting Strings
  • Variable Substitution

php assign by reference

IMAGES

  1. PHP Pass by Reference

    php assign by reference

  2. Assign by Reference with Ternary Operator in PHP

    php assign by reference

  3. PHP Pass By Reference

    php assign by reference

  4. PHP Call by Reference

    php assign by reference

  5. PHP References

    php assign by reference

  6. Call by Value & Call by Reference in PHP with Example

    php assign by reference

VIDEO

  1. Assign users permission using PHP/MySQL

  2. PHP Assign Multiple Values

  3. how to save selected option php

  4. Assign by Reference with Ternary Operator in PHP

  5. [Tutorial] PHP variable

  6. Урок 37. PHP. Типы данных. Передача по ссылке

COMMENTS

  1. PHP: Passing by Reference

    You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows: Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. The following things can be passed by reference:

  2. Reference assignment operator in PHP, =&

    The only thing that is deprecated with =& is "assigning the result of new by reference" in PHP 5, which might be the source of any confusion. ... Here's a handy link to a detailed section on Assign By Reference in the PHP manual. That page is part of a series on references - it's worth taking a minute to read the whole series. Share.

  3. PHP: Returning References

    You do not have to use & to indicate that reference binding should be done when you assign to a value passed by reference the result of a function which returns by reference. Consider the following two exaples:

  4. PHP: Basics

    PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa. To assign by reference, simply prepend an ampersand (&) to the ...

  5. Assign by Reference

    Assign by Reference. When we create a variable assigned to another variable, the computer finds a new space in memory which it associates with the left operand, and it stores a copy of the right operand's value there. This new variable holds a copy of the value held by the original variable, but it's an independent entity; changes made to ...

  6. In PHP, how does 'assign by reference' work with this new stdclass

    The important point is, if there is a reference, there must be some variable. Without a variable you can't have a reference in PHP. Share. Improve this answer. Follow edited Feb 26, 2012 at 11:47. answered Feb 26, 2012 at 11:42. hakre hakre. 195k 54 54 gold ... php assigning by reference,passing by reference. 0. PHP: references in assignment. 0.

  7. PHP Assignment Operators: Performing Calculations

    Anyway, assigning a reference in PHP is one of the language's benefits, enabling developers to set a value and refer back to it anywhere during the script-writing process. ... Assigning a Reference to a PHP Variable. Furthermore, individuals use the reference assignment operator =& to assign a reference to a variable rather than copying the ...

  8. PHP References: How They Work, and When to Use Them

    What exactly is a reference, anyway? A reference is simply a way to refer to the contents of a variable using a different name. In many ways, references are like file shortcuts in Windows, file aliases in Mac OS X, and symbolic links in Linux. Assigning by reference. An easy way to create a reference is known as assigning by reference. Consider ...

  9. How to pass PHP Variables by reference

    Scope of both global and function variable becomes global as both variables are defined by same reference. Therefore, whenever global variable is change, variable inside function also gets changed and vice-versa is applicable.

  10. How to re-code PHP assign-by-reference usage

    According to Deprecated features in PHP 5.3.x: Assigning the return value of new by reference is now deprecated. Call-time pass-by-reference is now deprecated. But assignment by reference in general is not deprecated, and Returning References says: To use the returned reference, you must use reference assigment

  11. PHP Tutorial => Assign by Reference

    Learn PHP - Assign by Reference. Learn PHP - Assign by Reference. RIP Tutorial. Tags; Topics; Examples; eBooks; Download PHP (PDF) PHP. Getting started with PHP; Awesome Book; ... Assigning by reference is not only limited to variables and arrays, they are also present for functions and all "pass-by-reference" associations.

  12. What Exactly Are PHP References?

    Besides assign by reference, another way to work with references in PHP is pass by reference. Pass by reference is when we pass arguments to a function via their references. More specifically, we label parameters in the function's definition as reference parameters. This is done by preceding the parameter with an ampersand (&), as shown below:

  13. php array assign by copying value or by reference? [duplicate]

    1 Depending on the types and values of the variables used as the array members, the copy operation may not happen at the time of the assignment even when assigned by-value. Internally PHP uses copy-on-write in as many situations as possible for reasons of performance and memory efficiency. However, in terms of the behaviour in the context of your code, you can treat it as a simple copy.

  14. Are arrays in PHP copied as value or as reference to new variables, and

    For the second part of your question, see the array page of the manual, which states (quoting):. Array assignment always involves value copying. Use the reference operator to copy an array by reference.

  15. Variable Assignment, Expressions, and Operators in PHP

    Assign by reference By default, PHP assigns all variables other than objects by value and not by reference. PHP has optimizations to make assignment by value faster than assigning by reference, but if you want to assign by reference you can use the & operator as follows:

  16. How to Pass Variables by Reference in PHP

    Defining Variables in PHP. As a rule, PHP variables start with the $ sign followed by the variable name. While assigning a text value to a variable, putting quotes around the value is necessary. In contrast to other programming languages, PHP doesn't have a command to declare a variable. It is generated at the moment a value is first assigned ...

  17. How to Use Assign by Reference, PHP Assign by Reference ...

    In this PHP coding practice, we take a look at, How to Use Assign by Reference, PHP Assign by Reference Explained, Codecademy PHP Variable Alias. We learn t...