PHP

Filter Array and Reset Numeric Keys

Master filtering arrays with `array_filter` and then resetting the numeric keys using `array_values`, a common pattern for clean, re-indexed result sets.

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter out odd numbers
$evenNumbers = array_filter($numbers, function($number) {
    return $number % 2 === 0;
});

// $evenNumbers would be [1 => 2, 3 => 4, 5 => 6, 7 => 8, 9 => 10]
// To reset keys to 0, 1, 2...
$reindexedEvenNumbers = array_values($evenNumbers);

// var_dump($reindexedEvenNumbers); // Expected: [2, 4, 6, 8, 10]

$data = [
    'apple' => 5,
    'banana' => 0,
    'cherry' => 10,
    'date' => 0,
    'elderberry' => 7
];

// Filter out items with value 0, then re-index
$filteredData = array_values(array_filter($data, function($value) {
    return $value > 0;
}));

// var_dump($filteredData); // Expected: [5, 10, 7]
How it works: This snippet illustrates a common PHP array pattern: filtering elements and then re-indexing the resulting array. `array_filter` removes elements that don't satisfy a given condition, but it preserves the original keys. `array_values` is then used to discard the old keys and assign new sequential numeric keys (starting from 0) to the filtered elements, providing a clean, re-indexed array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs