Data

Variable

PHP

 

Defining Variable

PHP 5
$age = 21;

$name = "Sam";

Variables are defined by assigning values to them.

Here we are defining two variables name and age.

Variable names are:

  • Case sensitive
  • Should be prefixed with $ sign.
  • Can contain letters, digits or _
  • Cannot start with a digit
 

Variable Types

PHP 5
$booleanVar = true;
$integerVar = 12;
$floatingPointVar = 1.618;
$stringVar = "Hello";
$arrayVar = [1, 2, 3];
$objectVar = (object)["name"=>"Sam", "age"=>21];
$nullVar = null;
$resourceVar = fopen("index.php",'r');

PHP Variables can be categorized in three groups:

  • Scalar Datatypes
    These are the most basic datatypes, which are: Boolean, Integer, Floating point and String types.

  • Compound Datatypes
    These are data types composed of other datatypes, which are Arrays and Objects.

  • Special Datatypes
    These are the types that are not Scalar or Compound. Null and Resource are in this category.

 

Type Safety

PHP 5
$status = 0;

$status = "success";

PHP unlike C and Java, is not a Type-Safe Language.

It automatically converts the variable to the correct data type, depending on its value.

 

Setting Variable value

PHP 5
$age = 21;  // defines $age with value 21

$age = 22;  // assign new value 22 to $age

Here, we are defining a variable age with value 21, then on the next statement, it assigns a value 22 to it.

 

Getting Variable value

PHP 5
$age = 21;

$samAge = $age + 3;   // samAge -> 24

To get the value of a variable, you can simply use its name.