haphpiness

These are things in PHP which make me genuinely_happy();

array_is_list() — Finally Answer "Is This Sequential?"

PHP has one array type that serves as both indexed arrays and associative maps. The question "is this a sequential list?" has been a recurring puzzle for decades. PHP 8.1 answered it definitively.

// An array is a "list" if keys are 0, 1, 2, ... in order
array_is_list([]);                        // true  — empty array
array_is_list(['a', 'b', 'c']);           // true  — sequential
array_is_list([0 => 'a', 1 => 'b']);      // true  — same thing

array_is_list(['a' => 1, 'b' => 2]);      // false — associative
array_is_list([1 => 'a', 0 => 'b']);      // false — wrong order
array_is_list([0 => 'a', 2 => 'c']);      // false — gap in keys

Before this, developers resorted to various imperfect heuristics: checking if array_keys($arr) === range(0, count($arr) - 1), or comparing json_encode outputs, or writing custom functions that iterated the entire array. All of them were slow, surprising, or both.

// Real-world use: serialise correctly based on structure
function toJson(array $data): string
{
    // array_is_list tells us whether to encode as [] or {}
    return json_encode($data, JSON_THROW_ON_ERROR);
    // json_encode already does this internally — now you can too
}

// Useful for input validation
function validateItems(array $items): void
{
    if (!array_is_list($items)) {
        throw new \InvalidArgumentException('Expected a list, got a map');
    }
}

Significance: Pragmatism

The dual-nature of PHP arrays is a source of endless subtle bugs in serialization, API responses, and data manipulation. array_is_list() is the escape hatch: a single, fast, unambiguous check that settles the question at the language level.