pTutorial

New way to learn PHP

PHP 5 Variable Assignment

PHP Variable Assignment

You might be familiar with an assignment by value, which simply assigns a particular value, such as the integer 1 or the string ciao, to a named variable.

There are two types of variable assignment in PHP

  • Assignment by Value
  • Assignment by Reference

Assignment by Value

It’s very common way to assignment of the variable generally we uses this method for assigning the value. Some examples of assignments by value are following below.

<?php

$num = 10;

$num1 = 10.25;

$str = "PHP";

echo "Integer=".$num."
"; echo "Float=".$num1."
"; echo "String=".$str."
"; ?>

These two assignment in the memory address represented by $num and $str and being assigned 10 and PHP.

Assignments by value can also take place through a return call in a function.

<?php

function simple ()

 {

$s =12 + 12;

return  $s;

}

$sum = simple();

echo $sum;

?>

When simple () function called it’s return sum of 24.

Assignment by Reference

Another way to assign a value to a variable is by referencing another variable’s, the other way to assign a value to a variable is by referencing another variable’s memory location. Instead of copying an actual value into the destination variable.

An assignment by reference is take place by using an ampersand (&).

<?php

$num=10;

$num1=&$num;

$num1=38;

echo "num1=". $num1."
";// print 120 echo "num=". $num; //print 120 ?>

As you can see above $num1 has been assigned $num memory location. Now any change in $num1 the result will be same because of pointing same memory location.


QUOTES OF THE DAY

Whenever man commits a crime,heaven finds a witness.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER