Skip to content

Instantly share code, notes, and snippets.

@terashim
Created December 27, 2023 09:18
Show Gist options
  • Save terashim/e9c5675978404d70ee894f86e5a104fc to your computer and use it in GitHub Desktop.
Save terashim/e9c5675978404d70ee894f86e5a104fc to your computer and use it in GitHub Desktop.
PHP配列の添え字が連番になっていないと `json_encode()` でJSONオブジェクトに変換される

PHP配列の添え字が連番になっていないと json_encode() でJSONオブジェクトに変換される。

$x = [0 => 'a', 1 => 'b'];
echo json_encode($x);
# => ["a","b"]

$x = [0 => 'a', 2 => 'b'];
echo json_encode($x);
# => {"0":"a","2":"b"}

array_filter() などを使ったときに添え字の欠落が起きやすい

$x = ['a', 'b', 'c'];
echo json_encode($x);
# => ["a","b","c"]

$x = array_filter($x, fn ($e) => $e != 'b');
echo json_encode($x);
# => {"0":"a","2":"c"}

array_values() で添え字を詰めればJSON配列に変換される

$x = array_values($x);
echo json_encode($x);
# => ["a","c"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment