The php variables are used to store the information in your php code. You can use the information anywhere in the php code by just mentioning the variable value.
Let’s create a simple code to run the variables.
1) Creating basic php tag.
[php]<?php echo "We will get the value here"; ?>[/php]
2) Declaring the variables.
[php]<?php
$txt = "Hello World";
$x = 5;
$y = 10.5;
?>[/php]
The above code has three variables. First “$text
” is given the information “Hello World
“. The equal sign “=
” indicates whenever I use “$txt
” in my php file always show me the result “Hello World
“. In a simple word, the “$txt
” is equal to “Hello World
“.
Similarly the “$x
” & “$y
” is holding the information “5
” & “10.5
” respectively.
3) Executing the result by using our favorite echo tag.
[php]<?php <br ?>
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "
";
echo $x;
echo "
";
echo $y;
?>[/php]
In the code, I have mentioned the variables and then I have to tell php code to echo means show me the result of “$txt
“, “$x
” & “$y
“.
Now the php will execute the code and show me the information of these variables as shown below.
Hello world!
5
10.5
You can see the information that I have provided to the variables are now executed successfully.
4) [php]"<br>" [/php] – I also added the break code which tells the php code to break the line and put the new result on the new line. It is useful for making the result neat. If you run the code without the break tag then you will get the result on the single line.
Hello world!510.5
You can see the code is not readable for a human. Only aliens can read this, so use [php]"<br>"[/php] to break the line.
Rules of PHP:
Follow them else you will get the error message
1) All text value in the variable should have single or double quotes around it. We have put the “hello world” text around double quotes. You can use single quotes as well. Do not forget to add semicolon “;
” sign at the end of each line.
$txt = "Hello world!";
or
$txt = 'Hello world!';
2) The variable should start with the dollar “$
” sign followed by the name of the variable.
$txt
3) There are only two ways of starting a variable name. Either you use proper text name or use underscore before the name. You are not allowed to use numbers at the beginning of the variable name.
Allowed
$txt
$_txt
Not allowed:
$9txt
$9_txt
4) You can use only alphanumeric characters or the underscores in the variables e.g. (A-z, 0-9, and _ )
5) The variable names are case sensitive. Use the proper format to get the result. For instance, $txt
and $TXT
are two different variables.