Variables store values in them. They can change as you perform operations. For example, you store a value like the number 5 in a php variable. Then you perform operations like additions, subtractions etc.
The first thing that you require for a variable is a name. PHP has the following rules for variable names:
- Variable names must start with the $ sign. For example: $a.
- After $, variable names can start with alphabets or underscore. For example: $_a
- After the first characters, variables can contain more alphabets or numbers and dashes. For example: $a_b1-C
- They are case sensitive. For example $a and $A are different or unique.
Using Variables
<?php $hello = "Hello World"; echo $hello; ?>
Output: Hello World
Variable values can change
Example:
<?php $hello = "Hello World"; echo $hello; echo "<br />"; $hello = 'Hi Again'; echo $hello; ?>
Output: Hello World Hi Again
Printing variables with other strings values
Example: <$php $hello = "Hello World"; echo $hello." and Goodnight"; $>
Output: Hello World and Goodnight
Strings and Numbers in PHP
Most of the time you will find yourself using string or numerical variable values in PHP.
Strings: Contains words and letters like “Hello World”
Numbers: Contains mathematical numbers like 1, 2, 2.5 etc. You can perform mathematical operations with such numbers.
Performing mathematical or arithmetic operations with variables
Example:
<?php $number1=20; $number2=10; echo $number1+$number2." "; //add echo $number1-$number2."<br />"; //subtract echo $number1*$number2."<br />"; //multiply echo $number1/$number2."<br />"; //divide echo $number1%$number2."<br />"; //modulus or finding the remainder when divided ?>
Output: 30 10 200 20 0
You can try a bit more complex arithmetic operations like (($number1+$number2)/$number2)+5.5.
There are other types of variables such as NULL and Boolean. I will write about them in the upcoming posts.
Constants in PHP
Constants remain the same. They have a name and that name holds a value. The value can never change. After defining the value once, the same name cannot be defined as a constant again.
Example:
<?php define("Name","Ashish"); echo Name; ?>
Output: Ashish