Contact for Expert ServicesAdvertise with Ecomspark.

PHP Type Juggling & Type Casting Tutorial

PHP Type Juggling-

In PHP, when we perform arithmetic operation on any expression that contain a string, that string interpreted as appropriate numeric data type for evaluating the expressions. So, if the string begins with one or more numeric character  then remaining string data will be ignored and if string begins with non numeric character, then it evaluates to zero .

For Example –

$var = "2"; /*  It's value will be 2 a numeric data type only */
$foo = "3";
$foo = $foo + "15 dos";
echo $foo ;

The output of this will be 18 only a numeric data type, as we know in string data type only numeric value is considered or evaluates to zero.

Note – If one of operand is float then output will be float value, otherwise output will be integer value only.

$foo "0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo $foo 1.3;  // $foo is now a float (3.3)
$foo "10 Hello world"// $foo is integer (15)
$foo "10 hello world";     // $foo is integer (15)

Above in 3rd row, $foo will be float value because one value is float.


 PHP Type Casting – While dealing with php variable data type, if we don’t like to use php automatic type juggling conversion feature then we can use php explicit type casting. In this, we use desired type in parenthesis before the variable which is to be cast.


$test = 10; /*  $etst is an integer */

$result = (boolean) $test ; /*  $result is boolean */


The casts allowed are:

  • (int), (integer) – cast to integer
  • (bool), (boolean) – cast to boolean
  • (float), (double), (real) – cast to float
  • (string) – cast to string
  • (array) – cast to array
  • (object) – cast to object
  • (unset) – cast to NULL (PHP 5)

Add a Comment

Your email address will not be published. Required fields are marked *

Translate »