Skip to content

Instantly share code, notes, and snippets.

@ijansch
Last active August 29, 2015 14:05
Show Gist options
  • Save ijansch/862ef3bee20f94f73815 to your computer and use it in GitHub Desktop.
Save ijansch/862ef3bee20f94f73815 to your computer and use it in GitHub Desktop.
2 common issues in php based apis
<?php
// Issue 1, empty associative arrays (dictionaries) become regular arrays.
$dictionary = array('key' => 'value');
var_dump(json_encode($dictionary)); // gives '{"key":"value"}';
unset($dictionary['key']);
var_dump(json_encode($dictionary)); // Gives '[]' -> json dictionary turned into array
var_dump(json_encode((Object)$dictionary)); // Gives '{}' -> json dictionary stays dictionary
// Issue 2, array manipulations that involve the array indexes, turn numeric arrays into dictionaries.
$fruits = array("apples", "oranges");
var_dump(json_encode($fruits)); // Gives ["apples", "oranges"]
unset($fruits[0]); // Don't like apples.
var_dump(json_encode($fruits)); // Gives '{"1":"oranges"}' -> wow, array turned into dictionary.
@ijansch
Copy link
Author

ijansch commented Sep 2, 2014

Ergo:

  1. unsetting elements in an associative array keeps it associative, until you unset the last element.
  2. unsetting elements in a numeric array makes it associative.

@ssx
Copy link

ssx commented Sep 2, 2014

I encountered this when dealing with an API a few weeks back and was an absolute nightmare to debug.

@sean9999
Copy link

sean9999 commented Sep 7, 2014

i had this problem dealing with mongoDB records. I pulled out most of my hair trying to debug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment