PHP Type Juggling


Definition and Usage

PHP is known as a dynamically typed language. Explicit type declaration of a variable is neither needed nor supported in PHP. Contrary to C, C++ and Java, type of PHP variable is decided by the value assigned to it, and not other way around. Further, a variable when assigned value of different type, its type too changes. This approach of PHP to deal with dynamically changing value of variable is called type juggling.

$var="Hello"; // variable is string type
$var=100; //same variable now becomes int

Type juggling also takes place during calculation of expression. In this example, a string variable containing digits is automatically converted to integer for evaluation of addition expression

Example

 Live Demo

<?php
$var1=100;
$var2="100";
$var3=$var1+$var2;
var_dump($var3);
?>

Output

This will produce following result −

int(200)

If a string starts with digits, trailing non-numeric characters if any, are ignored while performing calculation. However, PHP parser issues a notice as shown below

Example

<?php
$var1=100;
$var2="100 days";
$var3=$var1+var2;
var_dump($var3);
?>

Output

This will produce following result −

PHP Notice: A non well formed numeric value encountered in ...
int(200)

Type casting forces a variable to be used as a certain type. Following script shows example of different type cast operators

Example

 Live Demo

<?php
$var1=100;
$var2=(boolean)$var1;
$var3=(string)$var1;
$var4=(array)$var1;
$var5=(object)$var1;
var_dump($var2, $var3, $var4, $var5);
?>

Output

This will produce following result −

bool(true)
string(3) "100"
array(1) {
   [0]=>
   int(100)
}
object(stdClass)#1 (1) {
   ["scalar"]=>
   int(100)
}

Casting a variable to string can also be done by enclosing in double quoted string

Example

 Live Demo

<?php
$var1=100.50;
$var2=(string)$var1;
$var3="$var1";
var_dump($var2, $var3);
?>

Output

This will produce following result −

string(5) "100.5"
string(5) "100.5"

Updated on: 19-Sep-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements