array_unshift

(PHP 4, PHP 5, PHP 7, PHP 8)

array_unshiftPrepend one or more elements to the beginning of an array

Опис

array_unshift(array &$array, mixed ...$values): int

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be changed.

Зауваження:

Скидає внутрішній вказівник масиву на перший елемент.

Параметри

array

The input array.

values

The values to prepend.

Значення, що повертаються

Returns the new number of elements in the array.

Журнал змін

Версія Опис
7.3.0 This function can now be called with only one parameter. Formerly, at least two parameters have been required.

Приклади

Приклад #1 array_unshift() example

<?php

$queue
= [
"orange",
"banana"
];

array_unshift($queue, "apple", "raspberry");

var_dump($queue);

?>

Поданий вище приклад виведе:

array(4) {
  [0] =>
  string(5) "apple"
  [1] =>
  string(9) "raspberry"
  [2] =>
  string(6) "orange"
  [3] =>
  string(6) "banana"
}

Приклад #2 Usage with associative arrays

If one associative array is prepended to another associative array, the prepended array is numerically indexed into the former array.

<?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);

?>

Поданий вище приклад виведе:

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"
  }
}

Прогляньте також