During work with any language we make use of variables. Variables are used to store values and reuse them in our code. We use different types of variables in our code such as strings (text), integers (numbers), floats (decimal numbers), Boolean (true or false) and objects. In PHP we can make use of variable while writing scripts. In this lesson we’re going to cover PHP variables.
PHP Variable Syntax
$var_name = value;
Important Variable in PHP?
Some key points to notice:
(1) Remember to put the $ sign in front of variables when declaring variables in PHP.
(2)Variable names must start with letters or underscore.
(3) Variables can’t include characters except letters, numbers or underscore.
What is a variable?
A variable is a indicate to store values such as strings, integers or decimals so we can easily reuse those values in our code. For example, we can store a string value such as “Hello world” or an integer value of 100 into a variable.
PHP variable types?
Different Java or C++, PHP doesn’t care about primitive types. Any variable, a string, an integer or a float is declared the same way. PHP converts the types in the code by itself. Here’s what I mean.
//an integer variable $var_name = 300;
//an float variable $var_name = 300.00 ?>
PHP Variable type manage
Like talk about above, PHP doesn’t require variables to declared using primitive types. Therefore, manage between two types doesn’t require use of any special function. We can simply do things like…
//string var $var = “0″;
//var is now float $var += 8.5;
//var is now integer $var += 3;
//var is now string $var .= ” is the sum”; echo $var;
?>
Concatenating variables in PHP?
In PHP we can join two variables by using the dot ‘.’ operator.
$var1 = “Hello world”; $var2 = “and Java”;
//prints “Hello world and Java” echo $var1 . $var2;
$var1 = “1″; $var2 = “2″;
//prints “12″; echo $var1 . $var2;
?>
So there you have it, a quick and easy variable lesson in PHP.
You must be logged in to post a comment.