Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Related Rants
<?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"
undefined
php
gotcha