Predict the output · PHP
Array Key Casting
Hard Predict the output Seen at Booking.com, Automattic
What does this print?
What does this print?
<?php
$a = ["1" => "a", "01" => "b", true => "c", null => "d"];
var_dump(count($a));
echo json_encode($a);
int(4) {"1":"a","01":"b","true":"c","":"d"}int(3) {"1":"c","01":"b","":"d"}int(2) {"1":"c","":"d"}int(3) {"1":"a","01":"b","":"d"}
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
int(3)
{"1":"c","01":"b","":"d"} PHP normalises array keys: the decimal integer string "1" becomes int 1, true becomes 1 (overwriting "a" with "c" but keeping its position), and null becomes "". "01" is not a canonical integer string, so it stays a string key. Result: three keys.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium