Fonction PHP array_splice()
Exemple
Supprimez des éléments d'un tableau et remplacez-le par de nouveaux éléments :
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
Définition et utilisation
La fonction array_splice() supprime les éléments sélectionnés d'un tableau et les remplace par de nouveaux éléments. La fonction renvoie également un tableau avec les éléments supprimés.
Astuce : Si la fonction ne supprime aucun élément (longueur=0), le tableau remplacé sera inséré à partir de la position du paramètre de début (voir l'exemple 2).
Remarque : Les clés du tableau remplacé ne sont pas conservées.
Syntaxe
array_splice(array, start, length, array)
Valeurs des paramètres
Parameter | Description |
---|---|
array | Required. Specifies an array |
start | Required. Numeric value. Specifies where the function will start
removing elements.
0 = the first element.
If this value is set to a negative number, the function will start that far from the last element.
-2 means start at the second last element of the array. |
length | Optional. Numeric value. Specifies how many elements will
be removed, and also length of the returned array.
If this value is set to a negative number, the function will stop that far from the last element. If this value is not set, the function will
remove all elements, starting from the position set by the start-parameter.
|
array | Optional. Specifies an array with the elements that will be inserted to the original array. If it's only one element, it can be a string, and does not have to be an array. |
Détails techniques
Valeur de retour : | Renvoie le tableau composé des éléments extraits |
---|---|
Version PHP : | 4+ |
Plus d'exemples
Exemple 1
Le même exemple que l'exemple en haut de la page, mais la sortie est le tableau renvoyé :
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
print_r(array_splice($a1,0,2,$a2));
?>
Exemple 2
Avec le paramètre de longueur défini sur 0 :
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
❮ Référence de tableau PHP