Type Juggling in Depth
Type juggling is PHP changing a value from one type to another on its own. Arithmetic and loose comparisons trigger these changes.
Numeric strings act as numbers in arithmetic
Each string holds only digits, so each one juggles cleanly to a number. var_dump shows the result type is int both times.
<?php
var_dump("10" + 5);
var_dump("7" - 2);Loose comparison verdicts under the PHP 8 rules
The first two comparisons come out false. The last two come out true, because null juggles to 0 and the string "0" juggles to false.
<?php
var_dump(0 == "hello");
var_dump("" == 0);
var_dump(null == 0);
var_dump("0" == false);A mixed string warns and still adds
The string opens with a number and then holds a word. PHP warns that the value is not numeric, and it still adds the leading number.
<?php
var_dump("10 apples" + 5);empty verdicts hold a surprise
empty checks five values one by one. The string "0" counts as empty, but the string "0.0" does not.
<?php
var_dump(empty(""));
var_dump(empty("0"));
var_dump(empty(0));
var_dump(empty([]));
var_dump(empty("0.0"));Example
<?php
function formTotal($first, $second) {
return $first + $second;
}
var_dump(formTotal("12", "8"));
var_dump(formTotal("3", 4));Key points
- A numeric string holds digits as text, and arithmetic treats it as a number.
- A loose comparison with two equals signs juggles both sides before it compares them.
- A string that starts with a number but holds more text still gives its leading number to arithmetic.
- That mixed string also raises a warning, because the whole string is not numeric.
- empty reports true for an empty string, the string "0", the number 0 and an empty array.
- The string "0.0" is not empty, because it holds more than the single zero character.
In this example, formTotal adds two form inputs that arrive as strings. The strings "12" and "8" juggle to numbers and give int(20). The string "3" beside the number 4 gives int(7).
Note
A strict comparison with three equals signs skips juggling and checks the type too.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does var_dump("10" + 5) print?