Suppression d'un élément d'un tableau en PHP

Mots clés : phparraysunsetphp

meilleur 5 Réponses Suppression d'un élément d'un tableau en PHP

vote vote

90

$array = [0 => "a", 1 => "b", 2 => "c"]; unset($array[1]);           // ↑ Key which you want to delete 
[     [0] => a     [2] => c ] 
$array = [0 => "a", 1 => "b", 2 => "c"]; \array_splice($array, 1, 1);                    // ↑ Offset which you want to delete 
[     [0] => a     [1] => c ] 
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"]; $array = \array_diff($array, ["a", "c"]);                           // └────────┘                           // Array values which you want to delete 
[     [1] => b ] 
$array = [0 => "a", 1 => "b", 2 => "c"]; $array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);                                // ↑           ↑                                // Array keys which you want to delete 
[     [1] => b ] 
vote vote

82

$array = array(0, 1, 2, 3); unset($array[2]); var_dump($array); /* array(3) {   [0]=>   int(0)   [1]=>   int(1)   [3]=>   int(3) } */  $array = array(0, 1, 2, 3); array_splice($array, 2, 1); var_dump($array); /* array(3) {   [0]=>   int(0)   [1]=>   int(1)   [2]=>   int(3) } */ 
$array = array(0, 1, 2, 3);  unset($array[2]); $array = array_values($array); var_dump($array); /* array(3) {   [0]=>   int(0)   [1]=>   int(1)   [2]=>   int(3) } */ 
vote vote

77

  // Our initial array   $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");   print_r($arr);    // Remove the elements who's values are yellow or red   $arr = array_diff($arr, array("yellow", "red"));   print_r($arr); 
Array (     [0] => blue     [1] => green     [2] => red     [3] => yellow     [4] => green     [5] => orange     [6] => yellow     [7] => indigo     [8] => red )  Array (     [0] => blue     [1] => green     [4] => green     [5] => orange     [7] => indigo ) 
$arr = array_merge(array_diff($arr, array("yellow", "red"))); print_r($arr); 
Array (     [0] => blue     [1] => green     [2] => green     [3] => orange     [4] => indigo ) 
vote vote

62

$key = array_search($needle, $array); if ($key !== false) {     unset($array[$key]); } 
vote vote

60

unset($array[$index]); 

Questions similaires