4104 Contributors: 102 Thursday, June 22, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap



  • $variable = 'value'; // Assign general variable
  • $object->property = 'value'; // Assign an object property
  • ClassName::$property = 'value'; // Assign a static class property
  • $array[0] = 'value'; // Assign a value to an index of an array
  • $array[] = 'value'; // Push an item at the end of an array
  • $array['key'] = 'value'; // Assign an array value
  • echo $variable; // Echo (print) a variable value
  • some_function($variable); // Use variable as function parameter
  • unset($variable); // Unset a variable
  • $$variable = 'value'; // Assign to a variable variable
  • isset($variable); // Check if a variable is set or not
  • empty($variable); // Check if a variable is empty or not


Type checking

Some of the documentation regarding variables and types mentions that PHP does not use static typing. This is correct, but PHP does some type checking when it comes to function/method parameters and return values (especially with PHP 7).

You can enforce parameter and return value type-checking by using type-hinting in PHP 7 as follows:


 * Juggle numbers and return true if juggling was
 * a great success.
function numberJuggling(int $a, int $b) : bool
    $sum = $a + $b;

    return $sum % 2 === 0;

Note: PHP's gettype() for integers and booleans is integer and boolean respectively. But for type-hinting for such variables you need to use int and bool. Otherwise PHP won't give you a syntax error, but it will expect integer and boolean classes to be passed.

The above example throws an error in case non-numeric value is given as either the $a or $b parameter, and if the function returns something else than true or false. The above example is "loose", as in you can give a float value to $a or $b. If you wish to enforce strict types, meaning you can only input integers and not floats, add the following to the very beginning of your PHP file:


Before PHP 7 functions and methods allowed type hinting for the following types:

  • callable (a callable function or method)
  • array (any type of array, which can contain other arrays too)
  • Interfaces (Fully-Qualified-Class-Name, or FQDN)
  • Classes (FQDN)

See also: Outputting the Value of a Variable

Related Examples