Variables in PHP are similar to define and use as with other programming languages.  PHP uses loose typed variables, in other words they do not have to be defined specifically as a datatype upon initialization and can be changed to other data types using expressions.

To set a variable in PHP you only need to assign a value to it, for example $my_variable = “hello”;  Variable names start with a dollar sign $.  The next character must be a letter or underscore and the remaining characters may be letters, names or underscores.  PHP supports three different sets of data types:

  • Scalar Data Types: integer, float, string, boolean
  • Compound Data Types: array, object
  • Special Data Types: resource, null

There are several functions for checking and setting the type of a variable.  In some of the examples below I am using the echo command, which provides us with immediate output generated by the command.  Echo can often be used to print certain things including variables, arrays, etc on screen.

To Check a variable’s type:

echo gettype($variable);

 

Alternatively you can test to see if a variable is of a certain type (returned as either true or false) by using the is_int, is_float, isbook, is_array, is_object, isResource, is_null functions.

To Set a variable’s type:

settype($variable, "type")

 

Alternatively casting can be used when you only want to temporarily use the variable as a different type:

echo (type) $variable;

 

PHP Operators

[table id=2 /]

Constants

Constants are used in many programming languages and represent a value that will not change as a variable does.  Examples of constants could include configuration settings, which will remain the same throughout the script.  In PHP a constant can be defined using the define function:

define("MY_CONSTANT", "5.3"); // Setting the string 5.3