PHP

Filtering and Re-indexing Numeric Arrays in PHP

Learn how to efficiently filter elements from a PHP numeric array based on a callback function and then re-index the resulting array to remove any gaps in keys.

<?php

function filterAndReindexArray(array $data, callable $callback): array
{
    $filtered = array_filter($data, $callback);
    return array_values($filtered);
}

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

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

echo "Original numbers: " . implode(", ", $numbers) . "
";
echo "Odd numbers (filtered and re-indexed): " . implode(", ", $oddNumbers) . "
";

$products = [
    ['id' => 1, 'name' => 'Laptop', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'price' => 25],
    ['id' => 3, 'name' => 'Keyboard', 'price' => 75],
    ['id' => 4, 'name' => 'Monitor', 'price' => 300]
];

// Filter products with price > 100
$expensiveProducts = filterAndReindexArray($products, function($product) {
    return $product['price'] > 100;
});

echo "
Expensive products:
";
foreach ($expensiveProducts as $product) {
    echo "- " . $product['name'] . " ($" . $product['price'] . ")
";
}
?>
How it works: This snippet demonstrates how to filter array elements using `array_filter()` with a custom callback function, then re-index the resulting array using `array_values()`. This is crucial when you remove elements from a numerically indexed array and want to reset the keys to a sequential order, preventing gaps and ensuring consistent iteration.

Need help integrating this into your project?

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

Hire DigitalCodeLabs