json_encode したらどーなるかクイズ

突然ですが問題です。

<?php
array_unique(array_merge([1,2,3],[4]));

これの実行結果のprint_rはどうなるでしょうか?

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

簡単ですね。じゃあ、次は?

<?php
array_unique(array_merge([1,2,3],[2,3,4]));

mergeした結果をuniqueするのだから...

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [5] => 4
)

index番号に違いがあります。valueは同じです。

これらを踏まえて、次のjson_encodeの結果はどうなるでしょう?

<?php
json_encode(array_unique(array_merge([1,2,3],[4])));

簡単ですね。

[1,2,3,4]

はい。じゃあ、次は?

<?php
json_encode(array_unique(array_merge([1,2,3],[2,3,4])));

....

{"0":1,"1":2,"2":3,"5":4}

oh。配列だったのがオブジェクトに。

つまり、最初のような配列で必ずjson_encode結果を欲しい場合は array_uniqueしたものを array_valuesするか、再度 array_merge しないといけないらしい。

<?php
echo json_encode(array_values(array_unique(array_merge([1,2,3],[2,3,4]))));
// [1,2,3,4]

echo json_encode(array_merge(array_unique(array_merge([1,2,3],[2,3,4]))));
// [1,2,3,4]


PHPJSON返すAPI作ってたりすると自分と同じく嵌りそうな人もいるかと思うのでメモ。