Week 2: – Variables
In all programing languages like java, asp, c programs & … we use variable to show other values. Variables could be any value like numbers, names, etc. in this lesson we will understand what variables are and how to use and declare theme in PHP.
Definition of Variable
A variable is a data holder or container that holds values used in java programs and must be declared to use data type. There can be many data types. However, a variable could use one of eight primitive data types: byte, short, int, long, float, double, char or Boolean.
A Guide to Using Variables in PHP
As we said before that a variable is used to show another value, In PHP all variables start with the dollar sign ($). They can have numeric or string value.
<?php
$a = “NewWebster”;
//This sets the variable $a to a string value (NewWebster)
$b = 6;
//This sets the variable $b to a numeric value (6)
?>
Be noticed that string values take place inside quotations [""] while numeric values are not. Instead of just a static number, you can also set a variable equal to an equation. Here are some examples:
<?php
$a = 3 + 5;
//This sets the variable $a equal to 8 or (3 + 5)
$b = 6 + $a;
//This sets the variable $b equal to 14, or (6 + $a)
?>
We can combine values by using a period [.] This will mix and put one value after the other. Here is some example:
<?php
$a = 1;
$b = 2;
$c = $a.$b;
//The value of $c is now 12, because we smashed the 1 and 2 together
$d= $c + 1 ;
echo $d;
// This will echo 13, our newly created 12 plus 1 is 13
$e = “Number”;
$f = $e.$d;
echo $f;
//This will echo the string Number13, a combination of $e and $f
?>
You can also make a variable from a string by using this bracket {}. In this method, you can pass a string from one to another page and bye using that string you pull the data from a variable to the same name.
<?php
$a= “SomeVar”;
$SomeVar= “test”;
echo ${$a};
?>
This will display “test”, which is the value of variable “SomeVar” and you saw the example that it was a value of variable “a”.
Original Source: Prowebsters - php week 2