PHP Casting

Sometimes you need to convert a variable from one data type to another, or you want a variable to have a specific data type. This process is known as casting.

Tutorials dojo strip

Change Data Type

Casting in PHP is done with these statements:

  • (string) – Converts to data type String
  • (int) – Converts to data type Integer
  • (float) – Converts to data type Float
  • (bool) – Converts to data type Boolean
  • (array) – Converts to data type Array
  • (object) – Converts to data type Object
  • (unset) – Converts to data type NULL

Cast to String

To cast a variable to a string, use the (string) statement:

PHP

Cast to Integer

To cast a variable to an integer, use the (int) statement:

PHP

Cast to Float

To cast a variable to a float, use the (float) statement:

PHP

Cast to Boolean

To cast a variable to a boolean, use the (bool) statement:

PHP

If a value is 0, NULL, false, or empty, casting it to a boolean converts it to false. Otherwise, it converts to true. Even -1 converts to true.

Cast to Array

To cast a variable to an array, use the (array) statement:

PHP

Most data types convert into an indexed array with one element when cast to arrays. NULL values convert to an empty array.

Example: Converting Objects into Arrays

PHP

Cast to Object

To cast a variable to an object, use the (object) statement:

PHP

Most data types convert into an object with one property named “scalar” with the corresponding value. NULL values convert to an empty object.

Example: Converting Arrays into Objects

PHP

Cast to NULL

To cast a variable to NULL, use the (unset) statement:

PHP

Tutorials dojo strip