PHP
Remove First Occurrence of Value from Array
Learn how to efficiently remove the first occurrence of a specific value from a PHP array, re-indexing the array if needed.
<?php
function remove_value_from_array(array $array, mixed $valueToRemove, bool $reindex = true): array
{
if (($key = array_search($valueToRemove, $array, true)) !== false) {
unset($array[$key]);
}
return $reindex ? array_values($array) : $array;
}
$tags = ['php', 'javascript', 'html', 'css', 'php', 'mysql'];
$tagToRemove = 'php';
$tagsAfterRemoval = remove_value_from_array($tags, $tagToRemove);
// var_dump($tagsAfterRemoval); // Expected: ['javascript', 'html', 'css', 'php', 'mysql']
$userRoles = ['admin', 'editor', 'viewer', 'admin'];
$roleToRemove = 'admin';
$rolesAfterRemovalNoReindex = remove_value_from_array($userRoles, $roleToRemove, false);
// var_dump($rolesAfterRemovalNoReindex); // Expected: ['1' => 'editor', '2' => 'viewer', '3' => 'admin']
How it works: This snippet demonstrates how to remove the first occurrence of a specific value from an array. The `remove_value_from_array` function uses `array_search` to find the key of the value to be removed. If found, `unset()` removes that element. An optional `$reindex` parameter controls whether the array keys should be re-indexed using `array_values()` to create a clean, sequentially indexed array, or if the original keys should be preserved.