(PHP 4, PHP 5, PHP 7, PHP 8)
array_unshift — Empile un ou plusieurs éléments au début d'un tableau
Description
array_unshift(array
&$array, mixed
...$values): int
Note:
Réinitialise le pointeur interne du tableau au premier élément.
Liste de paramètres
-
array
-
Le tableau d'entrée.
-
values
-
Valeur à empiler.
Valeurs de retour
Retourne le nouveau nombre d'éléments du tableau
array.
Historique
Exemples
Exemple #1 Exemple avec array_unshift()
<?php
$queue = [
"orange",
"banana"
];
array_unshift($queue, "apple", "raspberry");
var_dump($queue);
?>
L'exemple ci-dessus va afficher :
array(4) {
[0] =>
string(5) "apple"
[1] =>
string(9) "raspberry"
[2] =>
string(6) "orange"
[3] =>
string(6) "banana"
}
Exemple #2 Utilisation avec des tableaux associatifs
Si un tableau associatif est ajouté en préfixe à un autre tableau
associatif, le tableau ajouté est indexé numériquement dans le tableau
précédent
<?php
$foods = [
'apples' => [
'McIntosh' => 'red',
'Granny Smith' => 'green',
],
'oranges' => [
'Navel' => 'orange',
'Valencia' => 'orange',
],
];
$vegetables = [
'lettuce' => [
'Iceberg' => 'green',
'Butterhead' => 'green',
],
'carrots' => [
'Deep Purple Hybrid' => 'purple',
'Imperator' => 'orange',
],
'cucumber' => [
'Kirby' => 'green',
'Gherkin' => 'green',
],
];
array_unshift($foods, $vegetables);
var_dump($foods);
L'exemple ci-dessus va afficher :
array(3) {
[0] =>
array(3) {
'lettuce' =>
array(2) {
'Iceberg' =>
string(5) "green"
'Butterhead' =>
string(5) "green"
}
'carrots' =>
array(2) {
'Deep Purple Hybrid' =>
string(6) "purple"
'Imperator' =>
string(6) "orange"
}
'cucumber' =>
array(2) {
'Kirby' =>
string(5) "green"
'Gherkin' =>
string(5) "green"
}
}
'apples' =>
array(2) {
'McIntosh' =>
string(3) "red"
'Granny Smith' =>
string(5) "green"
}
'oranges' =>
array(2) {
'Navel' =>
string(6) "orange"
'Valencia' =>
string(6) "orange"
}
}
Voir aussi
- array_merge() - Fusionne plusieurs tableaux en un seul
- array_shift() - Dépile un élément au début d'un tableau
- array_push() - Empile un ou plusieurs éléments à la fin d'un tableau
- array_pop() - Dépile un élément de la fin d'un tableau