Skip to main content

PHP Programming Tutorials for Beginners | PHP Variables Types

Welcome to PHPBash | Helping You to Become an Expert in PHP Programming. In this PHP Tutorial for beginners and professionals, we will learn about PHP Variables, PHP Variables Types, PHP Global Variables, php variable scope, static variable in php. As well Rules for Variable declaration.

PHP Programming Tutorials for Beginners | PHP Variables Types

This PHP tutorial covers all the topics of Basics of PHP Variable like
        1. 
PHP Variables
        2. Rules for Variable declaration
        3. Creating (Declaring) PHP Variable and Assigning value
        4. PHP Variable Scope & Lifetime
        5. PHP Static Variables
        6. Type Casting and Type Juggling in PHP
        7. 
PHP Variable Case Sensitiveness
        8. Destroying PHP Variables using unset()
        9. PHP Programming Examples/Scripts on PHP Variable concept
Now let's start  this tutorial with understanding PHP Variables.

PHP Variables

In computer programming, Variables are act as containers for storing data in to computer memory. Variables are named memory locations which stores data in to computer memory. The stored data in variables can be used by program for performing certain tasks. Whenever program needs variable value, it reads it from memory location. 
In PHP, Variable names must be starts with Dollar Sign($) followed by the name of variable that is to be created. 
Example
<?php
$msg="Welcome to PHP: First variable value";
?>
IMPORTANT:
1. In php, Variable names are always starts with $ Sign.
2. The value of variable is considered with the most recent assignment .
3. Variables can be initialized with = ( Assignment Operator).
4. In PHP, Variables are untyped means, Variable do not know, what value will be stored in it until actual assignment of value.
5. The Type casting or data type conversion handled by PHP implicitly.

Rules for Variable declaration

As variables are named memory location, we need to specify variable_name while creating PHP variable. While creating PHP Variable, there are following Rules need to be followed:
1. Variable in PHP language must start with a Sign of Dollar ($), followed by the variable name.
2. Variable name can contain alphanumeric character as well as underscore (A-z, 0-9, _).
3. A variable name can start with a letter or underscore (_) character.
4. PHP variable can not contain spaces.
5. PHP Variable names are case sensitive. For example, $COUNT and $Count are two different variables.
6. PHP variables are created at the instance, you assign value to it.
7. IMPORTANT: One thing to be kept in mind that the variable name cannot start with a number or special symbols.
Example of some valid variable names in PHP:
$test, $value99, $test_value1, $_count etc.

Example of some Invalid variable names in PHP:
9amount, $product id, $#value1 etc.

Creating (Declaring) PHP Variable and Assigning value

The PHP variable can be created or declared with before its use. After declaration of PHP variable, = (Assignment Operator) is used for assigning a value. The assignment operator stores or assigns value present on right side to the entity present on left side like variable. The following syntax can be used to declare variable.
Syntax
<?php
$variable_name=value;
?>
Example
<?php
// First variable: Integer 
$first=10;
// Second variable: Float or Double 
$second=10.10;
// Third variable: String
$third="I am String";
// Fourth variable:Boolean
$fourth=true;
// fifth variable: null
$fifth=null;
// Printing All variables
echo "First variable".$first."<br>";
echo "Second variable".$second."<br>";
echo "Third variable".$third."<br>";
echo "Fourth variable".$fourth."<br>";
echo "Fifth variable".$fifth."<br>";
?>
PHP The above program will print or displays all variable values one by one on new line because we used HTML <br> tag to break current line and start new line. In PHP, .(dot) operator is used for concatenating string value with variable value. 

PHP Variable Scope & Lifetime

The scope of variable is defined as the part/area of program or script where variable is valid for access. Lifetime of variable can be defined as the Execution time during which variable is available in memory for access or use. 
Basically, the Scope of variable is discussed in context of the area/part of program whereas Lifetime of variable is discussed in context of Execution time.In PHP, variables can be created anywhere in the script as per need.
Lets understand the concept of Scope and Lifetime with Example: If variable declared in a PHP function, then it will available for access only within that function(Between {...}) which is local scope. where as it will available in memory until function is executing which is Life time of variable. 
There are following types of Scope of PHP variable:
1. Local Scope- Only inside Specific Function
2. Global Scope- Inside whole script/program
Based on this, There are following types of PHP variables:
1. Local Variables: The local variables are declared and created inside a function.They are accessed only within function, in which they are declared. In other words, the variables declared within functions, cant be accessed outside of that function. 
In case of local variables, you can create a new variable with the same outside of that function. Both variables will be treated and used differently. Here function is block of statement written for performing particular task.
Consider following example which demonstrate use of PHP Local Variable:
<?php   
$count= 10;   

function test() 
{    
    // This $count is Local variable to this function 
    // the variable $count outside this function 
    // is a completely new variable 
    $count = 20; 
    echo "Local Variable Value = $count<br>";  //print 20 value 
}   
test(); // calling test() function 

// printing the value of $count variable 10
echo "The value is".$count;  
?>
2. Global Variables: As described, the variable can be declared anywhere in the PHP Script. Basically, Global variables in PHP are declared outside of a function. These variables are available for access to the whole PHP Script or PHP Program. You can access them inside a function as well with help of global keyword before variable name. Another way to do this is using $GLOBALS[index]. The index is nothing but the name of the variable. 
Example:
<?php   
//global variable
$count= 10;  
 
function test() 
  
// Accessing global variable $count inside function with global keyword
global $count; 
echo "Global Variable Value inside Function= $count<br>"; //print 10 value
echo "Global Variable Value inside Function= $_GLOBALS['count']<br>"; 
}
   
test(); // calling test() function 

// printing the value of $count variable 10
echo "The Global variable value outside Function".$count;  
?>
3. Static Variables: The variables are stored in memory only during Execution of PHP program or PHP Script. Once its Execution has completed, the variables are Kicked out or flush from memory and memory is released. In simple words, variables are destroyed on function Execution complete.  In some cases, we need to persist the value of variable after Execution of function is completed. so in Such scenario, PHP Static variables can be used whose value is stored even after the completion of Execution.
<?php  
   function static_demo() 
   {
      STATIC $ctr= 1;
      $ctr++;
      echo "The value of Counter is".$ctr."<br>";
   } 
   static_demo();
   static_demo();
   static_demo();
   static_demo();
   static_demo();
?>
In this case, the output will be
1
2
3
4
5

Type Casting and Type Juggling in PHP

PHP is a Loosely Typed Language. It means, while declaring variable, PHP do not force to declare the data type of variable like C,C++ which are strongly typed languages. For example, here while declaring the variable $count, we did not specify the data type int or integer. PHP automatically associates the data type based on value being assigned or stored in it. so here PHP will create $count, as Integer variable.
<?php   
$count= 10;   
echo "The value is".$count;  
?>
IMPORTANT: IN PHP 7, The data type declaration Added which forces to declare data type of variables.

PHP Type Casting or Data Type Conversion

The PHP Typecasting or Data type conversion is process of changing or converting one type of data in to another type of data. Basically, the data type of variable defines, what types of value or data is being stored in to variable. In PHP, there are various data types like Integer,Float/Double, String, Boolean, Array, Object, Resource, Null .
so we can change the type of data type of variable by modifying the value storing in it.
Example
<?php
// First variable: Integer 
$first=10;
// Second variable: Float or Double 
$first=10.10;
// Third variable: String
$first="I am String";
// Fourth variable:Boolean
$first=true;
// fifth variable: null
$first=null;
// Printing All variables
echo "First variable".$first."<br>";
?>
As shown in above example, data types are Type Casted automatically by PHP based on value assigned to variable. 
But you can also perform Explicit Type Casting where you will manually or explicitly specify datatype in which variable should be Type casted. PHP type casting is similar to that of C language. The settype() can be used for performing Explicit Typecasting in PHP.
Loot at below example of PHP Explicit Typecasting .
<?php
$ctr = 10;   // $ctr is an integer
$test = (boolean) $ctr;   // $test is a boolean
?>
Example of Explicit Typecasting with settype()
<?php
$one = "10 Pens"; // string
$two = true;   // boolean

settype($one, "integer"); // $one is now 10   (integer)
settype($two, "string");  // $two is now "1" (string)
?>

PHP Type Juggling

As PHP is loosely typed language, it does not required any explicit type definition while declaring variable. As stated earlier, the type of variable will be depend on what kind of value is stored in it. If $count is variable, and you stored String value in it. So PHP will treat or recognize $count as String Variable. If you store Integer  value, PHP will recognize $count variable as Integer. This is called PHP Juggling.
<?php
$one= "10";  // $one is string 
$one*= 2;   // $one is now an integer (20)
$one= $one* 1.0;  // $one is now a float (20.0)
$one= 5 * "5 Pens"; // $one is integer (25)
?>

PHP Variable Case Sensitiveness

PHP is Case Sensitive language means that, $PHPBash and $PHPBASH is different variable in PHP. In PHP, variable names are case sensitive. On other hand, regarding predefined keywords like while,for,if,switch,predefined functions, user defined functions, class names are incasesensitive in PHP.      
For Example:
<?php
    echo "PHP Case Sensitivity Test";
    ECHO "PHP Case Sensitivity Test";
?>
Both statements in above example will produce same result.
Look at another example:
<?php
$count = 1;
echo "Count  is " . $count. "<br>";
echo "Count is " . $COUNT. "<br>";
?>
In above example, only statement will print value of $count. The second statement will not print anything because $count and $COUNT are treated as different in PHP.  

Destroying PHP Variables using unset()

To destroy or unset a variable in PHP, the unset() function can be used. It needs the variable name as parameter which is to be unset or destroy.
<?php
function destroy_var() 
{
    global $ctr;
    unset($ctr);
}

$ctr = 10;
destroy_var();
echo $ctr;
?>

PHP Programming Examples / Scripts on PHP Variable concept

Example1: PHP Program for Addition of two numbers 
<?php
$a=10;
$b=20;
$c=a+b;
echo "Addition is".$c;
?>
Addition of two number in PHP
Addition of two number in PHP
Example 2: PHP Program for finding greatest among two numbers
<?php
$a=10;
$b=20;
if(a>b)
{
echo "a is greater".$a;
}
else
{
echo "b is greater".$b;
}
?>
Example 3: PHP Program for destroying variable using unset()
<?php
function test_unset() 
{
    unset($GLOBALS['ctr']);
}
$ctr = "Test Value";
test_unset();
?>
Example 4: PHP Program for Different variable types
<?php 
$first="I am string";  
$ctr=5;  
$area_circle=874.23;  
echo "STRING VARIABLE: $first <br/>";  
echo "INTEGER VARIABLE: $ctr <br/>";  
echo "FLOAT VARIABLE: $area_circle <br/>";  
?>

I would acknowledge you sharing your individual experiences about "PHP Variables Types". If you have any doubt/query related to PHP or Web Technologies, Please let me know in Comment Section. 
I will certainly take care that, I should give reply for every single comment on my blog posts. So, let’s fire the discussion up! See you in the comments section below..
 
 Sharing is caring ❤️

Thank you for Visiting PHPBashKeep Visiting for more Interesting concepts of Php language and web technologies from basics to advanced. 

As well we will also share some ready-to-use, useful code snippets for beginners to kick start their web development project. 

Do you want to build a modern, lightweight, responsive website and launch quickly? 

 I help to create the best websites / web applications and will be available for freelance work. Let's Get in touch: phpgems28@gmail.com

Comments

You may also like

PHP Constants

W elcome to PHPBash. In this PHP Tutorial, we will learn about Basics of PHP Constants.  In our Previous Tutorial , we learn about different concepts related to PHP variables. A constant is a name or an identifier with a fixed or permanent value. In Programming, Both constants and variables are used for storing data or values and act as container. Constants are more like variables with one difference that, Constants can not be modified/Changed during execution of program.  PHP Constants In this, PHP tutorial covers all the topics of Basics of PHP Constants  like         1.  PHP Constants         2.  Using the PHP define() method.         3.  Using the PHP const keyword.         4.  PHP 7 Constant Arrays         5.  PHP Global Constants         6.  PHP constant() Function          7. PHP Class constant array Now let's start  this tutorial with understanding P HP Constants and their use .  PHP Constants A constant is an identifier whose value cannot be changed or modified during the

PHP 7 Data Types: Scalar, Compound and Special

W elcome to PHPBash. In this PHP Tutorial, we will learn about Basics of PHP Data Types.  In our  Previous Tutorial , we learn about different concepts related to PHP variables.  Data types define what kind of data or values a variable will hold. With help of data types, computer can understand the type of data stored in variable and as per its type, memory will be allocated. so data types are very important and crucial concept in any programming language.  In PHP 7, there are total 10 different data type s. They are divided in to Scalar Types, Compound Types and Special Types. As PHP is loosely typed, there is no need to specify data type while declaring variables. PHP Handles typecasting or PHP Juggling automatically. You can read more about it, in this tutorial. In this, PHP tutorial covers all the topics of Basics of  PHP 7 Data Types  like 1.  PHP 7 Data Types and their Sub Types Now let's start  this tutorial with understanding  PHP 7 Data Types and  their  Sub Types. PHP 7

PHP echo and print Statements | PHP Echo Vs Print

Welcome to PHPBash. In this PHP Tutorial for Beginners , we will learn about PHP echo and print Statement. PHP print return 1 value where as PHP echo do not return any value. These both statements are used for printing output in PHP. The PHP echo or PHP print statement can be used for printing variables, strings, escaping characters etc.  PHP echo and print Statements | PHP Echo Vs Print  This PHP tutorial covers all the topics of Basics of PHP Variable like         1.  PHP Echo Statement         2.  PHP Echo Statement Example         3.  PHP  print   Statement         4.  PHP  print  Statement Example          5.  PHP Echo Vs Print  Now let's start  this tutorial with understanding  PHP Echo Statement with its Examples. In PHP, The output is displayed using either print or echo statements. For printing data, In PHP we can used print or echo statement. There is very small difference between print and echo statement. The print statement return value 1 where as echo do not return any

Basics of Php Syntax

Welcome to PHPBash | Helping You to Become an Expert in PHP Programming. In this PHP Tutorial for beginners and professionals, we will learn details about Precious Tips To Help You Get Better At Basics of PHP Syntax, Including PHP script in HTML and Executing PHP Script. As well  PHP case sensitivity, PHP tags and their types ,  Comments in PHP,  Whitespace in PHP &  PHP Block Concept. Basics of Php Syntax This PHP tutorial covers all the topics of Basics of PHP Syntax like           1. Basic PHP Syntax         2. PHP Case Sensitivity         3. Types of PHP Tags         4. Comments in PHP         5. White Spaces in PHP          6. Blocks in PHP          7. PHP Expressions and Statements          8. Executing/Running PHP Script in Windows Command Prompt(cmd) Now let's start  this tutorial with understanding Basic PHP Syntax. Basic PHP Syntax   PHP is very popular and most widely used and the reason is that,PHP is  simple to learn and use.   The code of PHP is executed on server

PHP Programming Fundamentals - Introduction to PHP

Welcome to PHPBash | Helping You to Become an Expert in PHP Programming. In this PHP Tutorial for beginners and professionals, I will provides in-depth knowledge of Introduction of PHP scripting language.  PHP Programming Fundamentals - Introduction to PHP  This PHP tutorial covers all the topics of PHP Introduction such as          1. What is PHP?         2. Basic Uses of PHP         3. Characteristics of PHP         4. Prerequisite to Start with PHP         5. What PHP File can contain?         6. Syntax of PHP Code          7.  What you will need to Work with PHP?  Let's start PHP tutorial with basic question, What is PHP? What is PHP? PHP Stands for PHP: hypertext Preprocessor. PHP is Open source general-purpose High Level  object-oriented  Scripting Language. It is used for web application development and can also be embedded into hypertext markup language (HTML).  Many Web site like Yahoo, Wikipedia,  Facebook,  Tumblr,  Wordpress,  MailChimp,  Flickr. etc, are developed usin

How to Beginning with your First PHP Program?

Welcome to PHPBash | Helping You to Become an Expert in PHP Programming. In this PHP Tutorial for beginners and professionals, I will Cover, How to Write First PHP Program or Script?, How to Execute PHP Program in XAMPP?,What PHP File contains? etc. To Run Your PHP Script, You must be ready with PHP Environment like XAMPP.  If you have not Installed XAMPP till now, You can Visit latest tutorial on  Installation of PHP with XAMPP in Windows 7/ Windows 10  from our blog. By Following instructions given in tutorial, you will be able to download and install XAMPP on Windows 7 / Windows 10. How to Beginning with your First PHP Program? This PHP tutorial covers all the topics of PHP Introduction such as          1. What is PHP Script/ PHP Program?         2. What PHP file Contains?         3. Editors for Writing PHP Program         4. Creating First PHP Program         5. Executing PHP Program in XAMPP      Lets start this PHP tutorial with question What is PHP Script/ PHP Program? What is P

PHP Comment Style Guide and Coding Standards

W elcome to PHPBash. In this PHP Tutorial, we will learn about Basics PHP Comments.  In our  Previous Tutorial , we learn about basics of PHP syntax as well fundamentals of comments. Basically, PHP Comments are part of PHP Program which is not executed by PHP  parser while Executing PHP Program. PHP Comments can be Single line or multiline.  PHP Comment Style Guide and PHP Coding Standards In this, PHP tutorial covers all the topics of Basics of  PHP Comments styles and Coding Standard  like 1.  What are Comments in PHP Programming Language?  2. Need of PHP Comments 3. Types of PHP Comments 4. PHP Comment Styling 5. PHP Comments Standards with Best Practices 6.PHP Comments Example with Valid and Invalid Examples Now let's start  this tutorial with understanding  What are Comments in PHP Programming Language? What are Comments in PHP Programming Language?  In PHP, Comments are part of PHP program or script which is not Interpreted by PHP Parser while Executing PHP Script or PHP prog

The Dummies Guide to Php.ini Configuration File of PHP

Welcome to PHPBash | Helping You to Become an Expert in PHP Programming. In this PHP Tutorial for beginners and professionals, I will cover details about The Dummies Guide to Php.ini Configuration File of PHP.  The configuration file (php.ini) of PHP is read when PHP starts up. In case of web server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI versions, it happens on every invocation. The Dummies Guide to Php.ini Configuration File of PHP Tutorial  This PHP tutorial covers all the topics of  php.ini File Configuration of PHP like         1. What is php.in file?         2. What are PHP Directives and their types?          3. Important settings or common parameters of the php.ini file Let's start PHP tutorial with questions, What is  php.in file ? What is php.in file? At the time of PHP installation, php.ini is a special file provided as a default configuration file. PHP's configuration file php.in is important file which is r

Installation of PHP with XAMPP in Windows 7/ Windows 10

Welcome to PHPBash | Helping You to Become an Expert in PHP Programming. In this PHP Tutorial for beginners and professionals, I will provides in-depth knowledge of Installation of PHP with XAMPP in Windows 7/ Windows 10. XAMPP can be used to install and configure PHP on Windows 7 / Windows 10. Installation of PHP with XAMPP in Windows 7/ Windows 10 This PHP tutorial covers all the topics of Installation of PHP with XAMPP in Windows 7/ Windows 10 such as          1. PHP Installation           2.  What is  XAMPP?         3. Alternative to XAMPP         4. Download XAMPP         5.  Installation of XAMPP in Windows 7/ Windows 10          Lets start PHP tutorial with PHP Installation . PHP Installation As described in our previous post, to install PHP we require three components that are PHP Parser, Web Server and Database Server. Collectively it is called as AMP Software Stack( Apache, MySql, PHP). We can download each component separately from their official websites. After download, w