PHP Variables and Data Types and Getting Output

PHP Variables

In all programming languages variables are containers which store information or data. For example if you want to store a number you have to store it in a variable. If you are familiar with C or C++ language then In C++ variables are declared with data type before using it in the program. For example integer variable is declared as int variable. PHP variables don’t need to declare . It is declared at the moment when it is created. It doesn’t need to declare data type too. In the given PHP program variable and its data type is not declared before using it in the program.
<?php
$a=30;
$b="PHP Script";
echo $a."<br>";
echo $b;
?>

The output of the above PHP script is:

30
PHP Script.

Some important things to remember:

  • PHP variables always start with $ sign.
  • After $ always use numbers, underscore and alphanumeric characters (Aa-Zz , 0-9 and _ ).
  • Variable name always start with a letter or underscore.
  • Variable name cannot be started with number.
  • In PHP variable name is case sensitive. Small letter and capital letter makes a big difference. For eample $a and $A are two different variables.

PHP has three variable scope. Global, local and static. Global has a scope in the entire program out of the function.It can onle be accessed outside the function. If you want to access global variabel inside the function you have to declare the same variable with global syntax inside the function.  While local has the scope inside the function. It cannot be accessed outside the function.

Example:

<?php
$b="PHP Script"; //Global Variable. It can be accessed outside the function
echo "$b";
function n()
{
$c=19; //Local Variable. It can only access within the function.
echo "$c";
global $a; //Here global is used to access global variable in function
echo $a;
}
n();

?>

Output of Above Program:

PHP variables
These are different data types in PHP which are:

  • Integer
  • Floats
  • String
  • Boolean
  • Array

For live example watch this video.

 

Leave a Reply

error: Content is protected !!