Variables and Consants in PHP – Strings and Numbers

PHP

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.
Make sure to keep your variable name simple, meaningful and convenient. For example: $myName, $data.

Using Variables

Example:
<?php
$hello = "Hello World";
echo $hello;
?>
Output:
Hello World
Note: Variables are not enclosed within quotes (” “) when printing them. But they still work when enclosed with double quotes.

Variable values can change

Example:

<?php
$hello = "Hello World";
echo $hello;
echo "<br />";
$hello = 'Hi Again';
echo $hello;
?>
Output:
Hello World
Hi Again
Note: Variable values can be enclosed within double quotes(” “) or single quotes (‘ ‘). While printing them, they cannot be enclosed with single quotes.

Printing variables with other strings values

Example:
<$php
$hello = "Hello World";
echo $hello." and Goodnight";
$>
Output:
Hello World and Goodnight
Note: Variables are concatenated or combined with a dot (.);

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
Note: Numbers do not require to be enclosed within quotes

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
Note: The value of constant Name always remains the same. It cannot be defined again. Notice there are no $ signs preceding Name.