Добавление элемента в массив PHP
Самый простой способ — с помощью квадратных скобок. Смотрите пример:
Результат выполнения кода:
Через array_push
Для добавления нового элемента в конец массива можно использовать функцию array_push . Смотрите пример:
Результат выполнения кода:
Через array_unshift
Для добавления нового элемента в начало массива можно использовать функцию array_unshift . Смотрите пример:
Результат выполнения кода:
array_push
array_push() использует array как стек и добавляет переданные значения в конец массива array . Длина array увеличивается на количество переданных значений. Имеет тот же эффект, что и выражение:
$array [] = $var ;
?>?php
повторенное для каждого переданного значения.
Замечание: Вместо использования array_push() для добавления одного элемента в массив, лучше использовать $array[] = , потому что в этом случае не происходит затрат на вызов функции.
Замечание: array_push() вызовет предупреждение, если первый аргумент не является массивом. Это отличается от поведения конструкции $var[] до PHP 7.1.0, в случае которой будет создан новый массив.
Список параметров
Значения, добавляемые в конец массива array .
Возвращаемые значения
Возвращает новое количество элементов в массиве.
Список изменений
| Версия | Описание |
|---|---|
| 7.3.0 | Теперь эта функция может быть вызвана с одним параметром. Ранее требовалось минимум два параметра. |
Примеры
Пример #1 Пример использования array_push()
$stack = array( «orange» , «banana» );
array_push ( $stack , «apple» , «raspberry» );
print_r ( $stack );
?>?php
Результат выполнения данного примера:
Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry )
Смотрите также
- array_pop() — Извлекает последний элемент массива
- array_shift() — Извлекает первый элемент массива
- array_unshift() — Добавляет один или несколько элементов в начало массива
User Contributed Notes 36 notes
11 years ago
If you’re going to use array_push() to insert a «$key» => «$value» pair into an array, it can be done using the following:
It is not necessary to use array_push.
15 years ago
I’ve done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.
$array = array();
for ( $x = 1 ; $x $array [] = $x ;
>
?>
takes 0.0622200965881 seconds
$array = array();
for ( $x = 1 ; $x array_push ( $array , $x );
>
?>
takes 1.63195490837 seconds
so if your not making use of the return value of array_push() its better to use the $array[] way.
Hope this helps someone.
7 years ago
Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do.
. but this is actually not true. Unlike array_push and even.
. Rodrigo’s suggestion is NOT guaranteed to append the new element to the END of the array. For instance.
$data[‘one’] = 1;
$data[‘two’] = 2;
$data[‘three’] = 3;
$data[‘four’] = 4;
. might very well result in an array that looks like this.
[ «four» => 4, «one» => 1, «three» => 3, «two» => 2 ]
I can only assume that PHP sorts the array as elements are added to make it easier for it to find a specified element by its key later. In many cases it won’t matter if the array is not stored internally in the same order you added the elements, but if, for instance, you execute a foreach on the array later, the elements may not be processed in the order you need them to be.
If you want to add elements to the END of an associative array you should use the unary array union operator (+=) instead.
$data[‘one’] = 1;
$data += [ «two» => 2 ];
$data += [ «three» => 3 ];
$data += [ «four» => 4 ];
You can also, of course, append more than one element at once.
$data[‘one’] = 1;
$data += [ «two» => 2, «three» => 3 ];
$data += [ «four» => 4 ];
Note that like array_push (but unlike $array[] =) the array must exist before the unary union, which means that if you are building an array in a loop you need to declare an empty array first.
. which will result in an array that looks like this.
[ «element1» => 1, «element2» => 2, «element3» => 3, «element4» => 4 ]
7 years ago
Unfortunately array_push returns the new number of items in the array
It does not give you the key of the item you just added, in numeric arrays you could do -1, you do however need to be sure that no associative key exists as that would break the assumption
It would have been better if array_push would have returned the key of the item just added like the below function
(perhaps a native variant would be a good idea. )
if(! function_exists ( ‘array_add’ )) function array_add (array & $array , $value /*[, $. ]*/ ) $values = func_get_args (); //get all values
$values [ 0 ]= & $array ; //REFERENCE!
$org = key ( $array ); //where are we?
call_user_func_array ( ‘array_push’ , $values );
end ( $array ); // move to the last item
$key = key ( $array ); //get the key of the last item
if( $org === null ) //was at eof, added something, move to it
return $key ;
>elseif( $org <( count ( $array )/ 2 ))< //somewhere in the middle +/- is fine
reset ( $array );
while ( key ( $array ) !== $org ) next ( $List );
>else while ( key ( $array ) !== $org ) prev ( $List );
>
return $key ;
>
>
echo «\n» ;
$pr = array( ‘foo’ => ‘bar’ , ‘bar’ => ‘foo’ );
echo «Taken array;» ;
print_r ( $pr );
echo «\npush 1 returns » . array_push ( $pr , 1 ). «\n» ;
echo «————————————\n» ;
$pr = array( ‘foo’ => ‘bar’ , ‘bar’ => ‘foo’ );
echo «\npush 2 returns » . array_push ( $pr , 1 , 2 ). «\n» ;
echo «————————————\n» ;
$pr = array( ‘foo’ => ‘bar’ , ‘bar’ => ‘foo’ );
echo «\n add 1 returns » . array_add ( $pr , 2 ). «\n\n» ;
echo «————————————\n» ;
$pr = array( ‘foo’ => ‘bar’ , ‘bar’ => ‘foo’ );
echo «\n add 2 returns » . array_add ( $pr , 1 , 2 ). «\n\n» ;
echo «\n\n» ;
?>
Outputs:
Taken array;Array
(
[foo] => bar
[bar] => foo
)
add 1 returns 0
add 2 returns 1
4 years ago
There is problem with pushing references to array, introduced in PHP 5.4 — did someone decide it is not needed?
In PHP 5.3 this could be used:
$A=array(); array_push($A,1); $c=2; array_push($A,&$c); print_r($A); $c=3; print_r($A);
Array ( [0] => 1 [1] => 2 )
Array ( [0] => 1 [1] => 3 )
Think of Reference as a pointer in other languages.
This function is needed for example to push parameters for MySql query:
$params=array(); array_push($params,&$field1); array_push($params,&$field2); array_unshift($params,’ss’);
call_user_func_array(array($Query,’bind_param’),$params);
This code causes fatal error in PHP 5.4 and depending on server configuration it may not even be reported why.
A workarround to allow pushing references to array is this:
$A=array(); $A[]=1; $c=2; $A[]=&$c; print_r($A); $c=3; print_r($A);
$params=array(); $params[]=&$field1; $params[]=&$field2; array_unshift($params,’ss’);
call_user_func_array(array($Query,’bind_param’),$params);
(in actual code, the fields are specified dynamically and iterated in for-loop. )
This seems working both on PHP 5.3 and PHP 5.6 .
15 years ago
If you’re adding multiple values to an array in a loop, it’s faster to use array_push than repeated [] = statements that I see all the time:
class timer
private $start ;
private $end ;
public function timer ()
$this -> start = microtime ( true );
>
public function Finish ()
$this -> end = microtime ( true );
>
private function GetStart ()
if (isset( $this -> start ))
return $this -> start ;
else
return false ;
>
private function GetEnd ()
if (isset( $this -> end ))
return $this -> end ;
else
return false ;
>
public function GetDiff ()
return $this -> GetEnd () — $this -> GetStart ();
>
public function Reset ()
$this -> start = microtime ( true );
>
echo «Adding 100k elements to array with []\n\n» ;
$ta = array();
$test = new Timer ();
for ( $i = 0 ; $i < 100000 ; $i ++)
$ta [] = $i ;
>
$test -> Finish ();
echo $test -> GetDiff ();
echo «\n\nAdding 100k elements to array with array_push\n\n» ;
$test -> Reset ();
for ( $i = 0 ; $i < 100000 ; $i ++)
array_push ( $ta , $i );
>
$test -> Finish ();
echo $test -> GetDiff ();
echo «\n\nAdding 100k elements to array with [] 10 per iteration\n\n» ;
$test -> Reset ();
for ( $i = 0 ; $i < 10000 ; $i ++)
$ta [] = $i ;
$ta [] = $i ;
$ta [] = $i ;
$ta [] = $i ;
$ta [] = $i ;
$ta [] = $i ;
$ta [] = $i ;
$ta [] = $i ;
$ta [] = $i ;
$ta [] = $i ;
>
$test -> Finish ();
echo $test -> GetDiff ();
echo «\n\nAdding 100k elements to array with array_push 10 per iteration\n\n» ;
$test -> Reset ();
for ( $i = 0 ; $i < 10000 ; $i ++)
array_push ( $ta , $i , $i , $i , $i , $i , $i , $i , $i , $i , $i );
>
$test -> Finish ();
echo $test -> GetDiff ();
?>
Output
$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html
Adding 100k elements to array with []
Adding 100k elements to array with array_push
Adding 100k elements to array with [] 10 per iteration
Adding 100k elements to array with array_push 10 per iteration
2 years ago
After using array_push you may wish to read the top (last) array element one or more times before using array_pop. To read the top array element efficiently, use the ‘current’ function.
5 years ago
There is a mistake in the note by egingell at sisna dot com 12 years ago. The tow dimensional array will output «d,e,f», not «a,b,c».
$stack = array( ‘a’ , ‘b’ , ‘c’ );
array_push ( $stack , array( ‘d’ , ‘e’ , ‘f’ ));
print_r ( $stack );
?>
The above will output this:
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => d
[1] => e
[2] => f
)
)
2 years ago
A common operation when pushing a value onto a stack is to address the value at the top of the stack.
This can be done easily using the ‘end’ function:
$top = end ( $stack );
?>
Note: See the ‘end’ function for details about its side effect on the seldom used internal array pointer.
17 years ago
If you push an array onto the stack, PHP will add the whole array to the next element instead of adding the keys and values to the array. If this is not what you want, you’re better off using array_merge() or traverse the array you’re pushing on and add each element with $stack[$key] = $value.
$stack = array( ‘a’ , ‘b’ , ‘c’ );
array_push ( $stack , array( ‘d’ , ‘e’ , ‘f’ ));
print_r ( $stack );
?>
The above will output this:
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => a
[1] => b
[2] => c
)
)
13 years ago
If you want to preserve the keys in the array, use the following:
function array_pshift (& $array ) <
$keys = array_keys ( $array );
$key = array_shift ( $keys );
$element = $array [ $key ];
unset( $array [ $key ]);
return $element ;
>
?>
4 years ago
This is how I add all the elements from one array to another:
$oneArray = [ ‘d’ , ‘e’ , ‘f’ ];
$anotherArray = [ ‘a’ , ‘b’ , ‘c’ ];
array_push ( $anotherArray , . $oneArray );
//[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’];
6 years ago
If the element to be pushed onto the end of array is an array you will receive the following error message:
Unknown Error, value: [8] Array to string conversion
I tried both: (and works, but with the warning message)
$aRol = array( $row[0], $row[1], $row[2] );
$aRoles[] = $aRol;
and
array_push( $aRoles, $aRol);
The correct way:
$cUnRol = implode(«(«,array( $row[0], $row[1], $row[2] ) );
array_push( $aRoles, $cUnRol );
7 years ago
When developing a pocketmine plugin, a good way to add stuff to a YAML table is
$table=$this->config->get(«Table»);
array_push($table, «New Value for table»);
$this->config->set(«Table», $table);
18 years ago
Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does. There’s another difference between array_push and the recommended empty bracket notation.
Empy bracket doesn’t check if a variable is an array first as array_push does. If array_push finds that a variable isn’t an array it prints a Warning message if E_ALL error reporting is on.
So array_push is safer than [], until further this is changed by the PHP developers.
14 years ago
elegant php array combinations algorithm
//by Shimon Dookin
function get_combinations(&$lists,&$result,$stack=array(),$pos=0)
$list=$lists[$pos];
if(is_array($list))
foreach($list as $word)
array_push($stack,$word);
if(count($lists)==count($stack))
$result[]=$stack;
else
get_combinations($lists,$result,$stack,$pos+1);
array_pop($stack);
>
>
$wordlists= array( array(«shimon»,»doodkin») , array(«php programmer»,»sql programmer»,»mql metatrader programmer») );
9 years ago
I think it worked in the past or i havent test it good enough. :-/
(once it worked, once [] was faster than array_push, the past 😀 ):
php -r ‘$a = array(1,2); $a += array(3,4); print_r($a);’
Array (
[0] => 1
[1] => 2
)
php -r ‘$a = array(1,2); $b = array(3,4);$c = $a + $b; print_r($c);’
Array (
[0] => 1
[1] => 2
)
php -r ‘$a = array(1,2); $b = array(2=>3,3=>4);$c = $a + $b; print_r($c);’
Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
8 years ago
I did a performance check, and I saw, if you push more than one value it can be faster the array push, that the normal $array[] version.
Case 1: $array[] = something;
Case 2: array_push($array, $value);
Case 3: array_push($array, $value1, $value2, $value3 [. ]); $values are definied
Case 4: array_push($array, $value1, $value2, $value3 [. ]); $values are definied, when $array is not empty
Case 5: Case1 + Case 3
Case 6: Result array contains some value (Case 4)
Case 7: Result array contains same value as the push array (Case 4)
————————————————————————————————————
~~~~~~~~~~~~ Case 1 ~~~~~~~~~~~~
Times: 0.0310 0.0300 0.0290 0.0340 0.0400 0.0440 0.0480 0.0550 0.0570 0.0570
Min: 0.0290
Max: 0.0570
Avg: 0.0425
~~~~~~~~~~~~ Case 2 ~~~~~~~~~~~~
Times: 0.3890 0.3850 0.3770 0.4110 0.4020 0.3980 0.4020 0.4060 0.4130 0.4200
Min: 0.3770
Max: 0.4200
Avg: 0.4003
~~~~~~~~~~~~ Case 3 ~~~~~~~~~~~~
Times: 0.0200 0.0220 0.0240 0.0340 0.0360 0.0410 0.0460 0.0500 0.0520 0.0520
Min: 0.0200
Max: 0.0520
Avg: 0.0377
~~~~~~~~~~~~ Case 4 ~~~~~~~~~~~~
Times: 0.0200 0.0250 0.0230 0.0260 0.0330 0.0390 0.0460 0.0510 0.0520 0.0520
Min: 0.0200
Max: 0.0520
Avg: 0.0367
~~~~~~~~~~~~ Case 5 ~~~~~~~~~~~~
Times: 0.0260 0.0250 0.0370 0.0360 0.0390 0.0440 0.0510 0.0520 0.0530 0.0560
Min: 0.0250
Max: 0.0560
Avg: 0.0419
~~~~~~~~~~~~ Case 6 ~~~~~~~~~~~~
Times: 0.0340 0.0280 0.0370 0.0410 0.0450 0.0480 0.0560 0.0580 0.0580 0.0570
Min: 0.0280
Max: 0.0580
Avg: 0.0462
~~~~~~~~~~~~ Case 7 ~~~~~~~~~~~~
Times: 0.0290 0.0270 0.0350 0.0410 0.0430 0.0470 0.0540 0.0540 0.0550 0.0550
Min: 0.0270
Max: 0.0550
Avg: 0.044
Tester code:
// Case 1
$startTime = microtime(true);
$array = array();
for ($x = 1; $x $array[] = $x;
>
$endTime = microtime(true);
// Case 2
$startTime = microtime(true);
$array = array();
for ($x = 1; $x array_push($array, $x);
>
$endTime = microtime(true);
// Case 3
$result = array();
$array2 = array(&$result)+$array;
$startTime = microtime(true);
call_user_func_array(«array_push», $array2);
$endTime = microtime(true);
// Case 4
$result = array();
for ($x = 1; $x $result[] = $x;
>
$array2 = array(&$result)+$array;
$startTime = microtime(true);
call_user_func_array(«array_push», $array2);
$endTime = microtime(true);
// Case 5
$result = array();
$startTime = microtime(true);
$array = array(&$result);
for ($x = 1; $x $array[] = $x;
>
$endTime = microtime(true);
// Case 6
$result = array(1,2,3,4,5,6);
$startTime = microtime(true);
$array = array(&$result);
for ($x = 1; $x $array[] = $x;
>
$endTime = microtime(true);
// Case 7
$result = array();
for ($x = 1; $x $result[] = $x;
>
$startTime = microtime(true);
$array = array(&$result);
for ($x = 1; $x $array[] = $x;
>
$endTime = microtime(true);
Добавить элемент в массив
Стоит отметить, что третий способ работает медленнее, чем первые два. Первые два способа просто добавляют элемент в конец массива, а для функции array_unshift() приходится ещё сдвигать индексы элементов.
array_push() и array_unshift() могут добавлять несколько элементов в массив, перечисленныe через запятую.
array_push($name, 'mysql', 'zend');
Обновлено: 01 ноября 2020
Комментарии
Авторизуйтесь, чтобы добавлять комментарии
Как добавить элементы в массив в PHP?
На самом деле, операция присваивания значений элементу массива (array) в PHP происходит так же, как и присваивание значений переменной. Но есть небольшая разница: квадратные скобки ([]), добавляемые после имени переменной массива, в данном случае не понадобятся (в таких скобках обычно указывают индекс/ключ элемента). Если же индекс/ключ указаны не будут, PHP выберет наименьший незанятый числовой индекс, сделав это автоматически:
php $my_arr = array( 0 => 'ноль', 1 => 'один'); $my_arr[2] = 'два'; $my_arr[3] = 'три'; var_dump($my_arr); // присваивание без указания ключа/индекса $my_arr[] = 'четыре'; $my_arr[] = 'пять'; echo "
"; var_dump($my_arr); ?>Таким образом, чтобы добавить элемент путём изменения определенного значения, следует просто присвоить новое значение элементу, который уже существует. А чтобы удалить какой-нибудь элемент PHP-массива с его ключом либо удалить сам массив полностью, применяется функция unset():
php $my_arr = array(10, 15, 20); $my_arr[0] = 'радуга'; // изменение значения 1-го элемента unset($my_arr[1]); // полное удаление 2-го элемента (ключ/значение) из массива var_dump($my_arr); unset($my_arr); // полное удаление массива ?>Тут нужно отметить, что если элемент добавляется в наш массив без ключа, язык программирования PHP автоматически станет использовать предыдущее самое большое значение ключа типа integer, увеличенное на 1. Когда целочисленные индексы в PHP-массиве отсутствуют, ключом становится 0.
Также учтите, что самое большее целое значение ключа совсем необязательно существует в нашем массиве в данный момент, что бывает при удалении элементов массива. А после удаления элементов переиндексация массива array не происходит. На словах всё достаточно сложно, лучше рассмотреть пример:
php // Создаётся простой массив с числовыми индексами $my_arr = array(1, 2, 3); print_r($my_arr); // Теперь удаляются все элементы, однако сам массив остаётся нетронутым: unset($my_arr[0]); unset($my_arr[1]); unset($my_arr[2]); echo "
"; print_r($my_arr); // Добавляется элемент (новым ключом станет 3 вместо 0). $my_arr[] = 6; echo "
"; print_r($my_arr); // Осуществляется переиндексация: $my_arr = array_values($my_arr); $my_arr[] = 7; echo "
"; print_r($my_arr); ?>В вышеописанном примере используются следующие функции: — array_values() — обеспечивает возвращение индексированного массива, заново индексируя возвращаемый массив числовыми индексами; — print_r() — работает как var_dump, однако осуществляет вывод массивов в более удобочитаемом виде.
Как добавить элементы в конец PHP массива?
Добавление одного или нескольких элементов можно выполнить, используя array_push() : int array_push ( array &$array , mixed $value1 [, mixed $. ] ). В нашем случае array_push используется как стек, добавляя переданные значения в конец array-массива. В результате длина array увеличится на количество переданных значений. Схожего эффекта можно достичь и с помощью следующего выражения, повторённого для каждого переданного значения:
php $array[] = $var; ?>Кстати, если нужно добавить только один элемент в PHP-массив, лучше задействовать не array_push, а $array[] = — в этом случае у нас не будет затрат на вызов функции.
Рассмотрим параметры работы:
array Наш входной массив. value1 1-е значение, добавляемое в конец нашего массива array.
Что касается возвращаемых значений, то будет возвращено новое количество элементов в массиве.
Рассмотрим использование array_push() на примере:
php $stack = array("banana , "orange"); array_push($stack, "raspberry", "apple"); print_r($stack); ?>В итоге получим:
Array ( [0] => banana [1] => orange [2] => raspberry [3] => apple )Как видите, ничего сложного. Если же интересует более сложная практика, её вы найдёте на нашем курсе по PHP-разработке:
