phplaravellaravel-resource

Why not mix string and numeric keys when using mergeWhen() with Laravel Resources


As one can read in the Laravel documentation, the following warning is stated:

The mergeWhen method should not be used within arrays that mix string and numeric keys. Furthermore, it should not be used within arrays with numeric keys that are not ordered sequentially.

However, I have tested this on my local machine and the method seems to behave like normal.

Thus this warning only leaves me wondering; why? Is this for security reasons? Performance? Maintainability? Or just some edge cases where the method does not behave correctly?

Digging further, looking at the Laravel Documentation with GitHub blame the warning seems to have been added by Taylor Otwell himself during an initial pass at the documentation, leaving me with no additional clues.


Solution

  • https://www.php.net/manual/en/language.types.array.php

    A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").

    Perhaps because of the implied conversion, therefore, there may be override. Perhaps that is what Taylor's warning is for, to PREVENT.

    If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

    Same with array_merge():

    https://www.php.net/manual/en/function.array-merge.php

    If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.