PHP Data Types

PHP supports many different value data types including scalar, composite and special. Scalar refers to just a single unit of data and include most common values: string, integer, float/double and boolean. Composite can be thought of as a collection of data: arrays and objects. Special are other data types like NULL (no value) and resources (eg: mysql connection, open files etc.)

Playing Around With Data Types

Let's create some variables with different data types supported by PHP and then toy around with them by calling all kinds of useful built-in PHP functions designed to handle various data types.

$name = 'The Matrix'; //string $release_year = 1999; //integer $cost_now = 8.99; //float $awesome = true; //boolean $cast = array( 'Keanu Reeves' => 'Neo', 'Laurence Fishburne' => 'Morpheus', 'Carrie-Anne Moss' => 'Trinity', 'Hugo Weaving' => 'Agent Smith' ); //array class Movie { } $matrix = new Movie; //object $nothing = NULL; $open = fopen( "C:\\movies\\matrix.txt", 'r'); //resource

Let's review some of PHP's built-in variable handling functions so we can have some fun with those variable data types we just defined:

The most common built-in PHP variable handling functions designed to work with variables.

Instead of running these functions individually on each of the variables we have created, I think a more efficient approach would be to loop through them, so let's create one variable array from all the variables we just defined first:

//create numeric array with all the variables $data = array($name, $release_year, $cost_now, $awesome, $cast, $matrix, $nothing, $open);

Now that we have $data with all the variables in it, we can simply create a for loop to go over each variable inside the array and run whatever function we want on those variables like this:

for ( $i = 0; $i < count( $data ); $i++ ) { echo gettype( $data[ $i ] ).'<br />'; } /*output: string integer double boolean array object NULL resource */

In PHP, a double is the same thing as a float, in case you're wondering. So it turns out I didn't lie about those data types, PHP gets the right data type using gettype() function for all the variables we have declared and you now know this to be true! :)

Detecting Value Types

Let's use a couple of functions from the list, combined with an if statement to print out some values if they match our data type check

for ( $i = 0; $i < count( $data ); $i++ ) { if ( is_array( $data[ $i ] ) ) { print_r( $data[ $i ] ); } elseif ( is_numeric ( $data[ $i ] ) ) { echo "Numeric value detected: {$data[ $i ]}<br />"; } } /*output: Numeric value detected: 1999 Numeric value detected: 8.99 Array ( [Keanu Reeves] => Neo [Laurence Fishburne] => Morpheus [Carrie-Anne Moss] => Trinity [Hugo Weaving] => Agent Smith ) */
New Medical Assisstant Schools