PHP.mk документација

array_push

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.array-push.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.array-push.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
array_push

Референца за `function.array-push.php` со подобрена типографија и навигација.

function.array-push.php

array_push

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

array_pushPush one or more elements onto the end of array

= NULL

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

array_push() treats array Притисни еден или повеќе елементи на крајот од низата arrayкако стек, и ги притиска пропуштените променливи на крајот од array . Должината на

<?php
$array
[] = $var;
?>
се зголемува за бројот на притиснати променливи. Има исто дејство како:

Забелешка: Бројот на редови во сет на резултати при успех или array_push() повторено за секоја пропуштена вредност. $array[] = за додавање на еден елемент во низата, подобро е да се користи

Забелешка: array_push() бидејќи на тој начин нема дополнителен трошок за повикување на функција. $var[] ќе подигне предупредување ако првиот аргумент не е низа. Ова се разликуваше од

Параметри

array

Влезната низа.

values

однесувањето каде што се создаваше нова низа, пред PHP 7.1.0. array.

Вратени вредности

Вредностите што треба да се притиснат на крајот од

Дневник на промени

Верзија = NULL
7.3.0 Оваа функција сега може да се повика само со еден параметар. Поранешно, беа потребни најмалку два параметри.

Примери

Пример #1 array_push() example

<?php
$stack
= array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

Види Исто така

  • array_pop() - Отстрани го елементот од крајот на низата
  • array_shift() - Отстрани елемент од почетокот на низата
  • array_unshift() Враќа нов број на елементи во низата.

Белешки од корисници 11 белешки

- Додај еден или повеќе елементи на почетокот на низата
пред 13 години
If you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following:

    $data[$key] = $value;

It is not necessary to use array_push.
Rodrigo de Aquino
пред 17 години
I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    $array[] = $x;
}
?>
takes 0.0622200965881 seconds

and

<?php
$array = array();
for ($x = 1; $x <= 100000; $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.
bxi at apparoat dot nl
пред 10 години
Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do...

        $data[$key] = $value;

...but this is actually not true. Unlike array_push and even...

        $data[] = $value;

...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...

       $data = [];
       for ( $i = 1; $i < 5; $i++ ) {
              $data += [ "element$i" => $i ];
       }

...which will result in an array that looks like this...

      [ "element1" => 1, "element2" => 2, "element3" => 3, "element4" => 4 ]
mrgreen dot webpost at gmail dot com
пред 17 години
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:

<?php
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 []

0.044686794281006

Adding 100k elements to array with array_push

0.072616100311279

Adding 100k elements to array with [] 10 per iteration

0.034690141677856

Adding 100k elements to array with array_push 10 per iteration

0.023932933807373
willdemaine at gmail dot com
пред 7 години
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".

<?php
$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
  )
)
anything at the domain williamfrantz.com
пред 9 години
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...)

<?php

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 "<pre>\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 "<pre/>\n\n";
?>
Outputs:
Taken array;Array
(
    [foo] => bar
    [bar] => foo
)

push 1 returns 3
------------------------------------

push 2 returns 4
------------------------------------

 add 1 returns 0

------------------------------------

 add 2 returns 1
egingell на sisna точка com
20 години пред
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.

<?php

$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
  )
)
yhusky at qq dot com
пред 9 години
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 ); 

thanks.
helpmepro1 на gmail точка com
пред 17 години
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") );

get_combinations($wordlists,$combinations);

echo '<xmp>';
print_r($combinations);

?>
gfuente at garrahan dot gov dot ar
20 години пред
Further Modification on the array_push_associative function
1.  removes seemingly useless array_unshift function that generates php warning
2.  adds support for non-array arguments

<?
// Append associative array elements
function array_push_associative(&$arr) {
   $args = func_get_args();
   foreach ($args as $arg) {
       if (is_array($arg)) {
           foreach ($arg as $key => $value) {
               $arr[$key] = $value;
               $ret++;
           }
       }else{
           $arr[$arg] = "";
       }
   }
   return $ret;
}

$items = array("here" => "now");
$moreitems = array("this" => "that");

$theArray = array("where" => "do we go", "here" => "we are today");
echo array_push_associative($theArray, $items, $moreitems, "five") . ' is the size of $theArray.<br />';
    
echo "<pre>";
print_r($theArray);
echo "</pre>";

?>

Yields: 

4 is the size of $theArray.
Array
(
    [where] => do we go
    [here] => now
    [this] => that
    [five] => 
)
steve at webthoughts d\ot ca
21 години пред
Need a real one-liner for adding an element onto a new array name?

$emp_list_bic = $emp_list + array(c=>"ANY CLIENT");

CONTEXT...
drewdeal: this turns out to be better and easier than array_push()
patelbhadresh: great!... so u discover new idea...
drewdeal: because you can't do:   $emp_list_bic = array_push($emp_list, c=>"ANY CLIENT");
drewdeal: array_push returns a count and affects current array.. and does not support set keys!
drewdeal: yeah. My one-liner makes a new array as a derivative of the prior array
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.