Home > DeveloperSection > Beginner > PHP Variables

PHP Variables


PHP PHP 
Ratings:
0 Comment(s)
 4426  View(s)
Rate this:

PHP Variables

 Variable is nothing more than a name of data storage location in computer memory. Variables are used for storing values, like text strings, numbers or arrays.

Syntax:  Declaring a variable in PHP.

$Variable_Name = value;

PHP is a loosely Typed Language:

In PHP, a variable does not need to be declared before assigning a value to it. In the above example, you see that you do not have to tell PHP, which types of variable it is. PHP automatically converts the variable to the correct data type, depending on its value. In a strongly typed programming language, you have to declare or define the type and name of the variable before using it.

Let’s we have an example, how to use variables in PHP script.

<html>

  <head>

        <title>PHP Variables</title>

  </head>

 <body>

        <?php

               // int type variable

                $intVar = 1024;

 

               // string type variable

               $stringVar   ="Hello";

 

               // char type varaible

               $charVar = 'A';

      

               // float type variable

               $floatVar    = 102.5260;

 

               echo "This is integer varaible";

                echo $intVar."</br>" ;

 

               echo "This is string variable :";

               echo $stringVar."</br>" ;

 

               echo "This is char variable :";

               echo $charVar."</br>" ;

      

               echo "This is float variable :";

               echo $floatVar."</br>";

        ?>

 </body>

</html>

 

 Desired output is:

PHP Variables

Naming Rule for declaring variables in PHP:

There is some rule to specify variables in PHP. The rules are…

1.       Variables name must start with letter or ‘_’ (Underscore).

2.       A variables name should not contains spaces. If a variable name is more than one word, it should be separated with ‘_’ (Underscore) (such as $var_name) or use capitalization word (such as $varName).

3.       A variables name can only contain alpha-numeric character (like $v123ar) and underscore.

 Example:  Let’s we have an example, Declaring alphanumeric, underscore variable etc.

<html>

  <head>

<title>Variable Convention</title>

</head>

<body>

       <?php

              // Declaring  '_' (underscore) variable

              $f_name = "Arun singh";

              // Declaring alpha-numeric variables

               $roll123no =123456;

             

              // print underscore variable

              echo $f_name ;

              // print alph-numeric varaible

              echo   $roll123no ;

        ?>

</body>

</html>

 

Desired output is:

PHP Variables


Don't want to miss updates? Please click the below button!

Follow MindStick