In php, assign values to variables and assign values to references. next I will introduce some of their basic usage and differences. 1. value assignment: Copy the value of the value assignment expression to the variable, the instance code is as follows:
In php, values are assigned to variables and references. next I will introduce some of their basic usage and differences.
1. value assignment: Copy the value of the value assignment expression to the variable. the instance code is as follows:
- $ Number = 15;
- $ Age = 20;
- $ Sum = 12 + "15"; // $ sum = 27
2. there are two methods to create an array: variable assignment and function call. here we will first talk about the former. the method to assign values to an array variable is very simple. the instance code is as follows:
-
- $ Lang [] = "php ";
- $ Lang [] = "html ";
- $ Lang [] = "css ";
- Echo "$ lang [0]
";
- Echo "$ lang [1]
";
- Echo "$ lang [2]
";
- >
Array content generated by the three assignment statements:
0 => php
1 => html
2 => css
3. reference value assignment: the created variable is the same as that referenced by another variable. Therefore, if multiple variables reference the same content, modify any of the variables, all other variables are reflected.
Add an & symbol ($ val2 = & $ val1) after the equal sign to complete the reference assignment or put the & symbol before the referenced variable ($ val2 = & $ val1 ), the code is as follows:
- $ Val1 = "hello ";
- $ Val2 = & $ val1;
- $ Val2 = "goodby ";
- Echo '$ val1 is'. $ val1 ."
- ";
- Echo '$ val2 is'. $ val2 ."
- ";
- ?>
- $ Val1 is goodby
- $ Val2 is goodby
The code for the foreach reference assignment is as follows:
-
- $ A = array (
- 'A' => 'A ',
- 'B' => 'BB ',
- 'C' => 'CC ',
- );
- Foreach ($ a as & $ v ){
- ;
- }
- Print_r ($ );
-
- Foreach ($ a as $ v ){
- }
- Print_r ($ );
If you think about it, it is actually a simple reference. after foreach is completed for the first time, $ v is actually a reference of $ a ['c']. during The Loop, each value assigned to $ v changes the value of $ a ['c']. the last value assigned to $ v is $ v = $ a ['c']. $ a ['c'] is assigned $ a ['B'] for the last time.