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);
  1. int(4)
    {"1":"a","01":"b","true":"c","":"d"}
  2. int(3)
    {"1":"c","01":"b","":"d"}
  3. int(2)
    {"1":"c","":"d"}
  4. 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.