Day 3 – Variables

Variable: variable is name of place where computer holds the value temporarily in computer’s memory (RAM), that we can use in our program. In PHP variable is defined with “$” sign.
In below program “$a” is a variable contain an integer value “23”, “$b” contain string value “Albert” and $c contain float value “232.44”.

Program 5: Define and display variables in php.

<?php
$a = 23;
$b = “Albert”;
$c = 232.44;
echo “Integer value of a is “.$a;
echo “<br/>String value of b is “.$b;
echo “<br/>Float value of c is “.$c;
?>

Note: “.” is used to concatenate string and variable.


Output:

Integer value of a is 23

String value of b is Albert

Float value of c is 232.44


Program 6: Sum of 2 Numbers with constants values.

<?php
$a = 2;
$b = 5;
echo “Sum of a and b is “.($a+$b);
?>

Output:

Sum of a and b is 7


Program 7: Swapping values of 2 variables with the help of 3rd variable.

<?php
$a = 4;
$b = 6;
$temp = 0;
echo “Value of a before Swapping “.$a;
echo “</br>Value of b before Swapping “.$b;
$temp = $a;
$a = $b;
$b = $temp;
echo “</br>Value of a after Swapping “.$a;
echo “</br>Value of b after Swapping “.$b;
?>

Output:

Value of a before Swapping 4

Value of b before Swapping 6

Value of a after Swapping 6

Value of b after Swapping 4


Program 8: Swapping values of 2 variables without taking 3rd variable.

<?php
$a = 4;
$b = 6;
echo “Value of a before Swapping “.$a;
echo “</br>Value of b before Swapping “.$b;
$a = $a + $b;
$b = $a – $b;
$a = $a – $b;
echo “</br>Value of a after Swapping “.$a;
echo “</br>Value of b after Swapping “.$b;
?>

Output:

Value of a before Swapping 4

Value of b before Swapping 6

Value of a after Swapping 6

Value of b after Swapping 4


Assignments:

  • Write a program to display multiply, difference and division of 2 numbers.
  • Write a program to display sum and average of 5 numbers.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.