An endpoint returns a list of notices. The happy path looks correct, but removing the first hidden notice makes the remaining item appear under an object key of 1. PHP arrays can represent either lists or maps, and the retained keys after filtering determine which JSON shape the encoder emits.

Enforce a list at both boundaries

Use a supported PHP CLI release such as PHP 8.3. Save this as list.php. The outer array must be a list, while the individual entries are application records with an already validated boolean visible field. Reindex only the outer list, not the fields inside the records.

<?php
declare(strict_types=1);

function visibleItems(array $items): string {
    if (!array_is_list($items)) {
        throw new InvalidArgumentException('Expected a list');
    }
    $kept = array_filter($items, static fn(array $item): bool => $item['visible']);
    return json_encode(array_values($kept), JSON_THROW_ON_ERROR);
}

$hidden = ['name' => 'draft', 'visible' => false];
$live = ['name' => 'notice', 'visible' => true];
$result = visibleItems([$hidden, $live]);
if ($result !== '[{"name":"notice","visible":true}]' ||
    visibleItems([$hidden]) !== '[]' || visibleItems([]) !== '[]') {
    throw new LogicException('Wrong response shape');
}
try {
    visibleItems([7 => $live]);
    throw new LogicException('Accepted an ID map');
} catch (InvalidArgumentException $expected) {
}
echo $result, PHP_EOL;

Run the syntax check and then execute the fixtures:

php -l list.php
php list.php

The second command prints:

[{"name":"notice","visible":true}]

Know when reindexing is appropriate

array_is_list checks whether the keys are consecutive integers beginning at zero, in that order. It also accepts an empty array. Filtering preserves keys, so the surviving notice still carries key 1 until array_values rebuilds the outer list. The nested object keeps its named fields. The invalid fixture illustrates why the list check comes before reindexing. If 7 is the notice's actual identifier, quietly dropping it would be a different bug. A service that needs both a list and the identifier should store the identifier as a record field.

Troubleshoot response shape

Test a leading removal, an all-hidden result, and a truly empty input. A fixture that removes only the last record may leave contiguous keys and hide the bug. If the contract calls for an object keyed by ID, use a different serializer and test the empty map explicitly. Avoid using JSON_FORCE_OBJECT as a patch for inconsistent arrays. It changes the representation in the opposite direction. The example throws on JSON encoding errors so invalid UTF-8 or another unsupported value cannot pass as an empty successful response.

Primary references and related tutorials: PHP array_is_list · PHP json_encode · Java Samples PHP tutorials.