Data

Literal

PHP

 

Literal Types

PHP 5
$booleanVar = true;
$integerVar = 12;
$floatingPointVar = 1.618;
$stringVar = "Hello";
$indexedArrayVar = [1, 2, 3];
$associativeArrayVar = ["name"=>"Sam", "age"=>21];
$nullVar = null;

Literals represent values, like: true, 12 or "Hello".

Literals in PHP can be grouped into these categories:

  • Boolean
  • Integer
  • Floating-point
  • String
  • Indexed Array
  • Associative Array
  • Null
 

Boolean Literal

PHP 5
$enable   = true;
$disable  = false;

There are 2 Boolean literals, true and false.

 

Integer Literal

PHP 5
$ans1 = 42;        // Base10
$ans2 = 0b101010;  // Binary
$ans3 = 052;       // Octal
$ans4 = 0x2A;      // Hexadecimal

There are 4 Integer Literal representations:

  • Base10
  • Binary (base 2)
  • Octal (base 8)
  • Hexadecimal (base 16)

All the variables defined here are equal to value 42.

 

Floating-Point Literal

PHP 5
$pi1 = 3.14159;   // Normal
$pi2 = 314159E-5; // Scientific

There are 2 Floating-point Literal representations:

  • Normal
  • Scientific

Both variables defined here are equal.

 

String Literal

PHP 5
$name1 = 'sam';
$name2 = "sam";

$name3 = <<<'EOT'
sam
EOT;

$name4 = <<<EOT
sam
EOT;

String is a sequence of characters.

There are 3 String Literal representations:

  • Single quoted
  • Double quoted
  • NowDoc
  • HereDoc

The differences between these Literals will be explained in the String topic.

 

Indexed Array Literal

PHP 5
$groceries = ["Milk", "Egg", "Corn"];

Array is an ordered sequence of items.

Here, We are creating an array of 3 elements named groceries.

Arrays will be discussed in the Array topic.

 

Associative Array Literal

PHP 5
$groceries = ["Milk"=>1, "Egg"=>6, "Corn"=>2];

Associative Array is a container for key/value pairs, in which keys are unique.

Here, We are creating an associative array of 3 elements named groceries, which each element is a key/value pair.

Arrays will be discussed in the Array topic.

 

Null Literal

PHP 5
$nextElement = null;

null is used to represent the absence of a value.