PHP

Remove Specific Values from an Indexed Array and Re-index

Discover how to remove one or more specific values from an indexed PHP array and then cleanly re-index the array to prevent gaps, using `array_diff` and `array_values`.

$originalArray = [1, 2, 3, 4, 5, 3, 6];
$valuesToRemove = [3, 5];

// Step 1: Remove the specified values
$filteredArray = array_diff($originalArray, $valuesToRemove);
print_r($filteredArray);
// Output: Array ( [0] => 1 [1] => 2 [3] => 4 [6] => 6 ) - Notice the skipped keys

// Step 2: Re-index the array to make it sequential again
$reIndexedArray = array_values($filteredArray);
print_r($reIndexedArray);
// Output: Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 6 )
How it works: This snippet demonstrates a two-step process to remove specific values from an indexed PHP array and ensure it remains sequentially indexed. First, `array_diff` compares the `originalArray` against `valuesToRemove` and returns an array containing only the values not found in `valuesToRemove`, preserving original keys. Second, `array_values` is used to re-index the resulting array numerically, closing any gaps left by the removed elements and ensuring a clean, sequential array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs