PHP - Introduction Type juggling

Introduction

Let's check another piece of code:

Demo

<?php
     $a = "1"; /*from www  .  j  av  a2 s .com*/
     $b = 2; 
     var_dump($a + $b); // 3 
     var_dump($a . $b); // 12 
?>

Result

The + operator returns the sum of two numeric values.

The . operator concatenates two strings.

Thus, the preceding code assigns a string and an integer to two variables, and then tries to add and concatenate them.

When trying to add them using +, PHP needs two numeric values, and so it tries to adapt the string to an integer.

In this case, the string represents a valid number.

That is the reason why we see the first result as an integer 3 (1 + 2).

In the last line, we are performing a string concatenation.

We have an integer in $b, so PHP will first try to convert it to a string-which is "2" and then concatenate it with the other string, "1".

The result is the string "12".

Type juggling

PHP tries to convert the data type of a variable when needed.

PHP does not change the value and type of the variable itself.

It will take the value and try to transform it, leaving the variable intact.

Related Topic