Cette question a plusieurs réponses mais je veux ajouter quelque chose de plus car lorsque j'ai utilisé unset
ou array_diff
j'ai eu plusieurs problèmes pour jouer avec les index du nouveau tableau lorsque l'élément spécifique a été supprimé (car les index initiaux sont enregistrés)
Je reviens à l'exemple:
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$array_without_strawberries = array_diff($array, array('strawberry'));
ou
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[array_search('strawberry', $array)]);
Si vous imprimez le résultat, vous obtiendrez:
foreach ($array_without_strawberries as $data) {
print_r($data);
}
Résultat :
> apple
> orange
> blueberry
> kiwi
Mais les index seront enregistrés et vous aurez donc accès à votre élément comme:
$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[3] > blueberry
$array_without_strawberries[4] > kiwi
Et donc le tableau final n'est pas réindexé. Vous devez donc ajouter après le unset
ou array_diff
:
$array_without_strawberries = array_values($array);
Après cela, votre tableau aura un index normal:
$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[2] > blueberry
$array_without_strawberries[3] > kiwi
Lié à cet article: Réindexer le tableau

J'espère que cela aidera