Link Search Menu Expand Document

Variable Types

In this section we’ll look it how types are assigned to variables in PHP scripts.

Table of Contents

  1. Variable Types in PHP
  2. Casting and Testing Variable Types
  3. NULL

Variable Types in PHP

PHP variables are dynamically typed, which means that they are not assigned types by the programmer. They are assigned a type by the interpreter based on their context.

Types in PHP:

  • boolean (scalar)
  • integer (scalar)
  • float (scalar)
  • string (scalar)
  • array (compound)
  • object (compound)
  • NULL (Variables can be assigned NULL or unset().)
  • resource (special)

Resources

Casting and Testing Variable Types

The type of a variable can be changed at any time by reassignment or by casting.

There are a number of is_*() functions available (example is_bool(), is_int(), &c) and isset() to check for NULL.

<?php

$my_int   = 12;
$my_float = (float)$my_int; // Casting int to a float.
unset($my_int); // Equivalent to: $my_int = NULL;
if (!isset($my_int) && is_float($my_float)) {
    echo "All is well.";
}

?>

Resources

NULL

A variable is considered NULL if:

  • It has not yet been assigned a value.
  • It has been explicitly assigned the constant NULL.
  • It has been unset().

We can test for null using isset().

<?php
    if (isset($new_variable)) {
        echo "How very odd!?!";
    }
    $new_variable = 'I am no longer NULL.';
    if (isset($new_variable)) {
        echo $new_variable;
    }
?>

Output:

I am no longer NULL.

Resources