3
torbuxx
7y

<?php
// This is the demo code of a PHP gotcha which took me some hours to figure out

$hr = "\n<hr>\n";
$JSON = '{"2":"Element Foo","3":"Element Bar","Test":"Works"}';
$array = (array)json_decode($JSON);

echo "Version: " . phpversion() . $hr;
// Tested on: 5.5.35 and 7.0.15

var_dump($array);
// Prints: array(3) { '2' => string(11) "Element Foo" '3' => string(11) "Element Bar" 'Test' => string(5) "Works" }

echo $hr;

var_dump($array['Test']);
// Prints: string(5) "Works"

echo $hr;

var_dump($array[2]);
var_dump($array['2']);
var_dump($array["2"]);
var_dump($array[3]);
var_dump($array['3']);
var_dump($array["3"]);
// Prints: NULL + Notice: Undefined offset ... in ...

echo $hr;

$newArray = array();
foreach ($array as $key => $value) $newArray[$key] = $value;

var_dump($newArray[2]);
var_dump($newArray['2']);
var_dump($newArray["2"]);
// Prints three times: string(11) "Element Foo"

var_dump($newArray[3]);
var_dump($newArray['3']);
var_dump($newArray["3"]);
// Prints three times: string(11) "Element Bar"

Comments
  • 1
    Php and using implicit type casting is like walking in a mine field and expecting to got out unharmed...

    Still cannot understand why some people think it is clever.

    (array) json_decode should be json_decode($json, true)

    Most of the stuff in PHP that you can use as a shortcut tend to have severe side effects, reason why I personally dislike some of the gotchas, as they sometimes lead people on dumb ideas. :)
Add Comment