Skip to content

Array Filter Converting JSON Data to Object #114

@kevinfodness

Description

@kevinfodness

Summary

The array_filter call here

return array_filter(
can cause the resulting data to become encoded in JSON as an object instead of an array if any elements other than just the last one are filtered out by the array_filter call.

Description

In PHP, when using array_filter, elements are removed from the array but the array is not re-indexed by default. When passing a non-sequentially-indexed array to json_encode, it encodes the element as an object with the numerical keys cast to strings. For example:

echo json_encode( array_filter( [ 'a', 'b', 'c' ], fn ( $item ) => 'b' !== $item ) );

Yields:

{"0":"a","2":"c"}

Impact

If the array_filter call linked above removes an item at the beginning or in the middle of the array, the data type of the block_data field changes from an array to an object, and any code that expects it to be an array will fail, especially JavaScript.

Resolution

In order to solve this problem, the array_filter call should be wrapped in a call to array_values which will cause PHP to renumber the array.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions