Как добавить элемент в начало массива php
Перейти к содержимому

Как добавить элемент в начало массива php

  • автор:

array_unshift

array_unshift() добавляет переданные в качестве аргументов элементы в начало массива array . Обратите внимание, что список элементов добавляется целиком, то есть порядок элементов сохраняется. Все числовые ключи будут изменены таким образом, что нумерация массива будет начинаться с нуля, в то время как строковые ключи останутся прежними.

Список параметров

Первое значение для добавления.

Возвращаемые значения

Возвращает новое количество элементов в array .

Примеры

Пример #1 Пример использования array_unshift()

array_unshift

array_unshift() добавляет переданные в качестве аргументов элементы в начало массива array . Обратите внимание, что список элементов добавляется целиком, то есть порядок элементов сохраняется. Все числовые ключи будут изменены таким образом, что нумерация массива будет начинаться с нуля, в то время как строковые ключи останутся прежними.

Замечание:

Сбрасывает внутренний указатель массива на первый элемент.

Список параметров

Значения для добавления.

Возвращаемые значения

Возвращает новое количество элементов в array .

Список изменений

Версия Описание
7.3.0 Теперь эта функция может быть вызвана с одним параметром. Ранее требовалось минимум два параметра.

Примеры

Пример #1 Пример использования array_unshift()

array_unshift ( $queue , «apple» , «raspberry» );
var_dump ( $queue );
?>

Результат выполнения данного примера:

Пример #2 Пример использования с ассоциативными массивами

Если один ассоциативный массив добавляется к другому ассоциативному массиву, то добавляемый массив продолжает числовой индекс первого массиве.

<?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_shift() — Извлекает первый элемент массива
  • array_push() — Добавляет один или несколько элементов в конец массива
  • array_pop() — Извлекает последний элемент массива

User Contributed Notes 12 notes

You can preserve keys and unshift an array with numerical indexes in a really simple way if you’ll do the following:

<?php
$someArray =array( 224 => ‘someword1’ , 228 => ‘someword2’ , 102 => ‘someword3’ , 544 => ‘someword3’ , 95 => ‘someword4’ );

$someArray =array( 100 => ‘Test Element 1 ‘ , 255 => ‘Test Element 2’ )+ $someArray ;
?>

now the array looks as follows:

array(
100=>’Test Element 1 ‘,
255=>’Test Element 2′
224=>’someword1′,
228=>’someword2′,
102=>’someword3′,
544=>’someword3′,
95=>’someword4′
);

array_merge() will also reindex (see array_merge() manual entry), but the ‘+’ operator won’t, so.

<?php
$arrayone =array( «newkey» => «newvalue» ) + $arrayone ;
?>

does the job.

Sahn’s example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc (& $arr , $key , $val )
<
$arr = array_reverse ( $arr , true );
$arr [ $key ] = $val ;
return = array_reverse ( $arr , true );
>
?>

Anonymous’ associative version wasn’t working for me, but it did with this small tweak:

function array_unshift_assoc(&$arr, $key, $val)
<
$arr = array_reverse($arr, true);
$arr[$key] = $val;
$arr = array_reverse($arr, true);
return $arr;
>

Another way to tack something to the beginning of an array is with array_merge().

$plans = array(‘AARP’=>’Senior’, ‘AAA’=>’Automobile Club’);

$plans = array_merge(array(«BAR»=>»Best Available Rate»), $plans);

This becomes a nice little problem if you index your arrays out of order (while manually sorting). For example:

<?php
$recordMonths [ 3 ] = ‘8/%/2006’ ;
$recordMonths [ 4 ] = ‘7/%/2004’ ;
$recordMonths [ 0 ] = ‘3/%/2007’ ;
$recordMonths [ 1 ] = ‘2/%/2007’ ;
$recordMonths [ 5 ] = ’12/%/2000′ ;
$recordMonths [ 6 ] = ’11/%/2000′ ;
$recordMonths [ 7 ] = ’10/%/2000′ ;
$recordMonths [ 2 ] = ‘1/%/2007’ ;

for( $i = 0 ; $i < count ( $recordMonths ); $i ++)
<
$singleMonth = $recordMonths [ $i ];
echo «singleMonth: $singleMonth <br />» ;
>
array_unshift ( $recordMonths , ‘%’ );
for( $i = 0 ; $i < count ( $recordMonths ); $i ++)
<
$singleMonth = $recordMonths [ $i ];
echo «singleMonth: $singleMonth <br />» ;
>
?>

Produces:

singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007

It reindexes them based on the order they were created. It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index. Just my opinion.

PHP array_unshift

Summary: in this tutorial, you will learn how to use the PHP array_unshift() function to prepend one or more elements to the beginning of an array.

Introduction to the PHP array_unshift() function

To prepend one or more elements to an array, you use the array_unshift() function:

  • $array is the input array
  • $values is the values to prepend

The array_unshift() returns the new number of elements in the array.

Note that the array_unshift() function modifies the original array. The array_unshift() function prepends the elements to the input array as a whole. It preserves the prepended elements.

Since the array_unshift() function adds the new elements to the beginning of the input array, it changes the indexes to start from zero.

PHP array_unshift() examples

Let’s take some examples of using the PHP array_unshift() function.

1) Using PHP array_unshift() function to prepend one element to an array example

The following example uses the array_unshift() function to prepend an element to the beginning of an array:

  • First, define an array with three elements.
  • Second, prepend the ‘new’ element to the beginning of the array.
  • Third, show the elements of the array using the print_r() function.

As you can see clearly from the output, the ‘new’ element gets the index zero while the existing indexes change accordingly.

2) Using PHP array_unshift() function to prepend one element to an array example

The following example uses the array_unshift() to prepend three elements to the beginning of an array:

Prepending an element to the beginning of an associative array

To prepend an element to an associative array, you use the + operator. For example:

PHP array_unshift() function

The array_unshift function inserts new values to the beginning of the array. In the case of the array with numeric keys, the newly inserted elements are assigned the numeric keys starting from 0 and increment by 1. However, string keys remain the same.

What is the syntax of the array_unshift function in PHP?

Parameter Description
array The array to insert new values to – Required
value1 Value to insert – Optional
value2 Next value to insert – Optional
value,… More values to insert – Optional

array_unshift function in PHP

Examples of array_unshift function

Example 1. Insert new values in an array with string keys.

Example 2. Insert new values in an array with numeric keys.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *