← Back to all snippets
PHP

Filter Array and Re-index Numerically

Filter elements from a PHP array based on a callback function and then re-index the resulting array numerically, useful for creating clean lists.

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

// Filter out even numbers
$oddNumbers = array_filter($numbers, function ($number) {
    return $number % 2 !== 0;
});

// Re-index the array to have sequential numeric keys
$reindexedOddNumbers = array_values($oddNumbers);

// print_r($oddNumbers); // Output: Array ( [0] => 1 [2] => 3 [4] => 5 [6] => 7 [8] => 9 ) (keys preserved)
// print_r($reindexedOddNumbers); // Output: Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 [4] => 9 ) (keys re-indexed)

$users = [
    10 => ['name' => 'Alice', 'status' => 'active'],
    20 => ['name' => 'Bob', 'status' => 'inactive'],
    30 => ['name' => 'Charlie', 'status' => 'active'],
];

$activeUsers = array_filter($users, function ($user) {
    return $user['status'] === 'active';
});

$reindexedActiveUsers = array_values($activeUsers);

// print_r($activeUsers); // Output: Array ( [10] => Array(...), [30] => Array(...) )
// print_r($reindexedActiveUsers); // Output: Array ( [0] => Array(...), [1] => Array(...) )
How it works: This snippet demonstrates a common pattern: first, `array_filter` is used to create a new array containing only elements that satisfy a given condition defined by the callback function. By default, `array_filter` preserves the original keys. To obtain a numerically re-indexed array, `array_values` is then applied to the filtered result, which discards the original string or non-sequential numeric keys and assigns new sequential integer keys starting from 0.

Need help integrating this into your project?

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

Hire DigitalCodeLabs