728x90

(PHP 4, PHP 5, PHP 7)

array_push — 배열의 끝에 하나 이상의 원소를 넣는다

설명 ¶

int array_push ( array &$array , mixed $var [, mixed $... ] )

array_push()는 array를 스택으로 취급하고, array 끝에 전달되어진 변수를 넣는다. array의 길이는 집어넣은 변수의 수만큼 증가한다. 다음과 같은 효과를 갖는다:

<?php
$array
[] = $var;
?>
각 var에 대해 반복된다.

Notearray_push()를 하나의 원소를 넣는 데 사용한다면, $array[] = 을 사용하는 것이 좋습니다. 함수 호출의 오버헤드가 없기 때문입니다.

Notearray_push()에 첫번째 인수가 배열이 아니면 경고가 발생합니다. 이는 새 배열이 생성될 때 $var[] 동작과 다릅니다.

인수 ¶

array

입력 배열.

var

넣을 값.

반환값 ¶

배열에 새로 추가된 원소의 수를 반환한다.

예제 ¶

Example #1 array_push() 예제

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

위 예제의 출력:

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

참고 ¶

  • array_pop() - 배열의 마지막 원소 빼내기
  • array_push()
  • array_unshift() - 배열의 맨 앞에 하나 이상의 원소를 첨가
add a note add a note

User Contributed Notes 29 notes

Rodrigo de Aquino ¶
5 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:

    $data[$key] = $value;

It is not necessary to use array_push.
bxi at apparoat dot nl ¶
9 years ago
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.
andrew at cgipro dot com ¶
12 years ago
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
aaron dot hawley at uvm dot edu ¶
12 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.
mrgreen dot webpost at gmail dot com ¶
1 year ago
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 ]
willdemaine at gmail dot com ¶
9 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:

<?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
egingell at sisna dot com ¶
11 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.

<?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
  )
)
kamprettos at yahoo dot com Teguh Iskanto ¶
12 years ago
Looking for a way to push data into an associative array and frustrated to know that array_push() can't do the job ? 

here's my Scenario : 
-------------------
I need to relate system command output into an associative array like these :

[sge@digital_db work]$ /usr/local/apache/htdocs/work/qhost.sh -h t1 -F | awk '{if(NR>4) print $1}' | sed  's/hl://g' 
arch=lx24-amd64
num_proc=2.000000
mem_total=3.808G
swap_total=3.907G
virtual_total=7.715G
load_avg=0.000000
load_short=0.000000
load_medium=0.000000
load_long=0.000000
mem_free=3.510G
swap_free=3.907G
virtual_free=7.417G
mem_used=305.242M
swap_used=0.000
virtual_used=305.242M
cpu=0.000000
np_load_avg=0.000000
np_load_short=0.000000
np_load_medium=0.000000
np_load_long=0.000000

how I did it :
<? php

# get into the system command output 
$assoc_cmd =`$work_dir/qhost.sh -h $host_resource -F | awk '{if(NR>4) print $1}'| sed  's/hl://g' ` ;

# split the "\n" character 
$assoc_row = explode("\n", chop($assoc_cmd));

# get the index row 
$idx_row  = count($assoc_row) - 1 ;

# initialize the associative array 
$host_res_array = array();

for ($i = 0 ; $i<= $idx_row ; $i++) 
        {       
                # get params & values 
                list($host_param,$host_val) = explode("=",$assoc_row[$i]);

                # populate / push data to assoc array 
                $host_res_array[$host_param]= $host_val ;
        }    

echo "<pre> Architecture : </pre>\n" ;
echo $host_res_array['arch'] ;
echo "<pre> Mem Total    : </pre>\n" ;
echo $host_res_array['mem_tot'];

?>

Hope this helps ! :)
aosojnik at gmail dot com ¶
8 years ago
If you want to preserve the keys in the array, use the following: 

<?php 
function array_pshift(&$array) { 
    
$keys array_keys($array); 
    
$key array_shift($keys); 
    
$element $array[$key]; 
    unset(
$array[$key]); 
    return 
$element

?>
bk at quicknet dot nl ¶
12 years ago
Add elements to an array before or after a specific index or key:

<?php

/**
* @return array
* @param array $src
* @param array $in
* @param int|string $pos
*/
function array_push_before($src,$in,$pos){
    if(
is_int($pos)) $R=array_merge(array_slice($src,0,$pos), $inarray_slice($src,$pos));
    else{
        foreach(
$src as $k=>$v){
            if(
$k==$pos)$R=array_merge($R,$in);
            
$R[$k]=$v;
        }
    }return 
$R;
}

/**
* @return array
* @param array $src
* @param array $in
* @param int|string $pos
*/
function array_push_after($src,$in,$pos){
    if(
is_int($pos)) $R=array_merge(array_slice($src,0,$pos+1), $inarray_slice($src,$pos+1));
    else{
        foreach(
$src as $k=>$v){
            
$R[$k]=$v;
            if(
$k==$pos)$R=array_merge($R,$in);
        }
    }return 
$R;
}

// Examples:

$src=array("A","B","C");
$in=array("X","Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "X"
  [2]=>
  string(1) "Y"
  [3]=>
  string(1) "B"
  [4]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "X"
  [3]=>
  string(1) "Y"
  [4]=>
  string(1) "C"
}*/

$src=array('a'=>"A",'b'=>"B",'c'=>"C");
$in=array('x'=>"X",'y'=>"Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, key array, before index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_before($src,$in,'b'));
/* array_push_before, key array, before key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, key array, after index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,'b'));
/* array_push_after, key array, after key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

?>
helpmepro1 at gmail dot com ¶
9 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") );

get_combinations($wordlists,$combinations);

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

?>
gfuente at garrahan dot gov dot ar ¶
11 months 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 ); 

thanks.
colecooper2005 at icloud dot com ¶
1 year 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);
raat1979 at gmail dot com ¶
1 year 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...)

<?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) !== $orgnext($List);
        }else{
            while (
key($array) !== $orgprev($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
golddragon007 ¶
2 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 <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);

// Case 2
    $startTime = microtime(true);
    $array = array();
    for ($x = 1; $x <= 100000; $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 <= 100000; $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 <= 100000; $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 <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);

// Case 7
    $result = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        $result[] = $x;
    }
    $startTime = microtime(true);
    $array = array(&$result);
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);
flobee ¶
4 years ago
Be warned using $array "+=" array(1,2,3) or union operations (http://php.net/manual/en/language.operators.array.php)

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 :-D ): 

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
)
Chicna ¶
5 years ago
I found a simple way to have an "array_push_array" function, without the references problem when we want to use call_user_func_array(), hope this help : 

function array_push_array(array &$array)
{
    $numArgs = func_num_args();
    if(2 > $numArgs)
    {
      trigger_error(sprintf('%s: expects at least 2 parameters, %s given', __FUNCTION__, $numArgs), E_USER_WARNING);
      return false;
    }
    
    $values = func_get_args();
    array_shift($values);
   
    foreach($values as $v)
    {
      if(is_array($v)) 
      {
        if(count($v) > 0) 
        {
          foreach($v as $w)
          {
            $array[] = $w;
          }
        }
      }
      else 
      {
        $array[] = $v;
      }
    }
    
    return count($array);
}
rarioj at gmail dot com ¶
8 years ago
This function "Returns the new number of elements in the array."

To find out the last index, use:

<?php
$count 
array_push($array$value);
$last_index array_pop(array_keys($array));
?>
wesleys at opperschaap dot net ¶
9 years ago
A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

<?php

function array_push_array(&$arr) {
    
$args func_get_args();
    
array_shift($args);

    if (!
is_array($arr)) {
        
trigger_error(sprintf("%s: Cannot perform push on something that isn't an array!"__FUNCTION__), E_USER_WARNING);
        return 
false;
    }

    foreach(
$args as $v) {
        if (
is_array($v)) {
            if (
count($v) > 0) {
                
array_unshift($v, &$arr);
                
call_user_func_array('array_push',  $v);
            }
        } else {
            
$arr[] = $v;
        }
    }
    return 
count($arr);
}

$arr = array(0);
$arr2  = array(6,7,8);
printf("%s\n"array_push_array($arr, array(),array(1,2,3,4,5), $arr2));
print_r($arr);

# error.. 
$arr "test";
printf("%s\n"array_push_array($arr, array(),array(1,2,3,4,5), $arr2));

?>
alexander dot williamson at gmail dot com ¶
9 years ago
This will work to solve the associative array issues:

$aValues[$key] = $value;

Where $key is a unique identifier and $value is the value to be stored. Since the $key works off a string or number, if you already have a $key with the same value as an existing $key, the element will be overwritten.

e.g.

$aValues["one"] = "value of one";
$aValues["two"] = "different value of two!";

gives:
array([one] => "value of one", [two] => "value of two");

but will be overwritten when using the same key (one):

$aValues["one"] = "value of one";
$aValues["one"] = "different value of two!";

will give:

array([one] => "different value of two!");

3686
zbde00 at hotmail dot com ¶
10 years ago
A very good function to remove a element from array 
function array_del($str,&$array)
{
    if (in_array($str,$array)==true) 
    {
    
        foreach ($array as $key=>$value)
        {
            if ($value==$str) unset($array[$key]);
        }
    }
}
Marc Bernet ¶
11 years ago
A small and basic implementation of a stack without using an array.

class node
{
        var $elem;
        var    $next;
}
class stack
{
    var $next;
    function pop()
    {
        $aux=$this->next->elem;
        $this->next=$this->next->next;
        return $aux;
    }
    function push($obj)
    {
        $nod=new node;
        $nod->elem=$obj;
        $nod->next=$this->next;
        $this->next=$nod;
    }
    function stack()
    {
        $this->next=NULL;
    }     
}
steve at webthoughts d\ot ca ¶
12 years ago
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] => 
)
john ¶
12 years ago
A variation of kamprettos' associative array push:

// append associative array elements
function associative_push($arr, $tmp) {
  if (is_array($tmp)) {
    foreach ($tmp as $key => $value) { 
      $arr[$key] = $value;
    }
    return $arr;
  }
  return false;
}

$theArray = array();
$theArray = associative_push($theArray, $items);
ciprian dot amariei at gmail com ¶
12 years ago
regarding the speed of oneill's solution to insert a value into a non-associative array,  I've done some tests and I found that it behaves well if you have a small array and more insertions, but for a huge array and a little insersions I sugest  using this function:

function array_insert( &$array, $index, $value ) {
   $cnt = count($array);

   for( $i = $cnt-1; $i >= $index; --$i ) {
       $array[ $i + 1 ] = $array[ $i ];
   }
   $array[$index] = $value;
}

or if you are a speed adicted programmer (same situation: big array, few insertions) use this:

array_splice ( $array, $offset, 0, $item );

item may also be an array of values ;).
Phil Davies ¶
12 years ago
As someone pointed out the array_push() function returns the count of the array not the key of the new element. As it was the latter function i required i wrote this very simple replacement.

function array_push2(&$array,$object,$key=null){
    $keys = array_keys($array);
    rsort($keys);
    $newkey = ($key==null)?$keys[0]+1:$key;
    $array[$newkey] = $object;
    return $newkey;
}
bart at framers dot nl ¶
16 years ago
Array_push also works fine with multidimensional arrays. Just make sure the element is defined as an array first. 

<?php 
$array
["element"][$element]["element"] = array(); 
array_push ($array["element"][$element]["element"], "banana"); 
?>
yuri ¶
6 years ago
If you want to put an element to a specific position in an array, try this function.

<?php

function array_put_to_position(&$array$object$position$name null)
{
        
$count 0;
        
$return = array();
        foreach (
$array as $k => $v
        {   
                
// insert new object
                
if ($count == $position)
                {   
                        if (!
$name$name $count;
                        
$return[$name] = $object;
                        
$inserted true;
                }   
                
// insert old object
                
$return[$k] = $v
                
$count++;
        }   
        if (!
$name$name $count;
        if (!
$inserted$return[$name];
        
$array $return;
        return 
$array;
}
?>

Example :

<?php
$a 
= array(
'a' => 'A',
'b' => 'B',
'c' => 'C',
);
            
print_r($a);
array_put_to_position($a'G'2'g');
print_r($a);

/*
Array
(
    [a] => A
    [b] => B
    [c] => C
)
Array
(
    [a] => A
    [b] => B
    [g] => G
    [c] => C
)
*/
?>
oneill at c dot dk ¶
12 years ago
To insert a value into a non-associative array, I find this simple function does the trick:

function insert_in_array_pos($array, $pos, $value)
{
  $result = array_merge(array_slice($array, 0 , $pos), array($value), array_slice($array,  $pos));
  return $result;
}

Seems an awful lot simpler than the iterative solutions given above...


728x90
<?php
/**
* Created by JetBrains PhpStorm.
* User: kangnaru
* Date: 13. 10. 12.
* Time: 오전 10:18
* To change this template use File | Settings | File Templates.
*/
$arr = array(1, 3, 9, 2);
array_push($arr,10);
array_push($arr,13);
print_r($arr);
?>


앞에 반드시 요소가 있어야 하는 것은 아니다.


<?php

$arr = Array();

array_push($arr, 10); 


?>


과 같이도 사용 가능하다

728x90

I am relatively new to programming and OOP in PHP. I tried to create a Simple Login Register Script using my basic knowledge of OOP. I'm sure my code can be better in a lot of way. I'm trying to code better and learn new things.

Be harsh, please find out as many small noob mistakes as you can. Suggestions and Feedbacks are always welcomed !

Config.php

<?php 
class dbConfig {
   public $host;
   public $username;
   public $password;
   public $dab;
   public $conn;

public function dbConnect() {
    $this->conn = mysqli_connect($this->host,$this->username,$this->password);

    if (!$this->conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    else{
        echo "Connected successfully to server";
    }

    $db_selected = mysqli_select_db($this->conn, $this->dab);

    if (!$db_selected) {
        // if the given database doesn't exists
        // creates new database with that name
        $db_sql = 'CREATE DATABASE chatapp';

        // verify the database is created
        if (mysqli_query($this->conn, $db_sql)){
            echo "Database chatapp already exists or created successfully\n";
        } else {
            echo 'Error creating database: ' . mysqli_error() . "\n";
        }
    }

    // creating tables
    $table_sql = "CREATE TABLE IF NOT EXISTS users (".
            "uid INT PRIMARY KEY AUTO_INCREMENT,".
            "username VARCHAR(30) UNIQUE,".
            "password VARCHAR(50),".
            "name VARCHAR(100),".
            "email VARCHAR(70) UNIQUE); ";

    // verify the table is created
        if (mysqli_query($this->conn, $table_sql)) {
            echo "Table: users already exists or created successfully\n";
        } else {
            echo 'Error creating table: ' . mysqli_error($table_sql) . "\n";
        }
}
}

$obj = new dbConfig();

$obj->host = 'localhost';
$obj->username = 'root';
$obj->password = '';
$obj->dab = 'chatapp';
$obj->dbConnect();

login.php

<?php
include('config.php');
session_start();

if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$emailusername = mysqli_real_escape_string($obj->conn,$_POST['emailusername']); 
$password = mysqli_real_escape_string($obj->conn,$_POST['password']); 
$password = md5($password);

$sql="SELECT uid FROM users WHERE username='$emailusername' or email = '$emailusername' and password='$password'";
$result=mysqli_query($obj->conn,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$active=$row['active'];
$count=mysqli_num_rows($result);


// If result matched $username and $username, table row must be 1 row
if($count==1)
{
$_SESSION['login_user'] = $emailusername;
header("location: welcome.php");
}
else 
{
$error="Your Login Name or Password is invalid";
}
}
?>
<<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <form action="login.php" method="post">
        <label>UserName or Email:</label>
        <input type="text" name="emailusername"/><br />
        <label>Password :</label>
        <input type="password" name="password"/><br/>
        <input type="submit" value=" Submit "/><br />
    </form>
</body>
</html>

register.php

    <?php
include('config.php');
if(isset($login_session))
{
header("Location: login.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST") 
{
$username = mysqli_real_escape_string($obj->conn,$_POST['username']); 
$password = mysqli_real_escape_string($obj->conn,$_POST['password']); 
$name     = mysqli_real_escape_string($obj->conn,$_POST['name']); 
$email    = mysqli_real_escape_string($obj->conn,$_POST['email']); 

$password = md5($password);

$sql ="SELECT uid from users WHERE username = '$username' or email = '$email'";
$register_user = mysqli_query($obj->conn,$sql) or die(mysqli_error($sql));
$no_rows = mysqli_num_rows($register_user);

if($no_rows == 0)
{
    $sql2 = "INSERT INTO users(username, password, name, email) values ('$username', '$password', '$name', '$email')";
    $result = mysqli_query($obj->conn, $sql2) or die(mysqli_error($sql2));
    echo "Registration Successfull!";
}
else{
    echo "Registration Failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
</head>
<body>
    <form action="register.php" method="post">
    <label>UserName or Email:</label>
    <input type="text" name="username" required/><br />
    <label>Password :</label>
    <input type="password" name="password" required/><br/>
    <label>Full Name :</label>
    <input type="text" name="name" required/><br/>
    <label>Email :</label>
    <input type="email" name="email" required/><br/>
    <input type="submit" value=" Submit "/><br />
    </form>
</body>
</html>

logout.php

<?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>

welcome.php

<?php
include('lock.php');
?>
<html>
<head><title>Home</title>
</head>
<body>
<h1>Welcome <?php echo $login_session; ?></h1>
</body>
</html>

lock.php

<?php
include('config.php');
session_start();
$user_check=$_SESSION['login_user'];

$ses_sql=mysqli_query($obj->conn,"SELECT username FROM users WHERE username='$user_check' ");

$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

$login_session=$row['username'];

if(!isset($login_session))
{
header("Location: login.php");
}
?>

While copy-pasting the code here, I was getting feeling that I made the code a bit more lengthier for such a small task. Please let me know how to minify the code and other various aspects of my code.

shareimprove this question

At first glance

After a quick glance at your code, it reminded me of this review I posted a while back. Much like that piece of code, a couple of (broadly similar) issues jumped out:

  • Wrapping procedural style code in a class with some methods does not qualify as OOP.
  • Your one and only method (dbConnect) is fundamentally flawed and unsafe. Not in the least because it relies on the user (the code that creates an instance of your class) to set the properties manually before calling the method. What if these properties aren't set? create a __construct method (constructor) that requires the user to pass the connection params to the class when an instance is created, much in the same way that mysqli or PDO require these params to be passed.
  • There is some sanitation of values used in your query, but you really ought to look into prepared statements
  • Methods don't echo, and they certainly don't die. If they encounter a problem, they throw new RuntimeException, or some other exception that accurately describes the problem (InvalidArgumentExceptionBadMethodCallException, ...).
  • Your dbConnect method just does too much. Its name suggests it merely connects, when in reality, it echoes, creates tables and never closes the DB connection. Calling dbConnecttwice is possible, your code doesn't take that into account.
  • Coding standards are important. PHP doesn't have any official standards (yet), but the PHP-FIG standards are adopted by all major players (Symfony, Zend, Apple, Composer, CakePHP, ...). You'd do well following them, too
  • md5, as a hash, is no longer secure. It first started showing weaknesses back in 1998, was deemed unsafe about ten years ago, and back in 2010, a single-block collision was found. At the very least, use sha1, but even so: PHP supports blowfish, sha256 and sha512 just as easily.
  • When hashing passwords, you'd also do well using salt. Don't just hash the password as-is. Add some random string that only you know. Even so, PHP has a very useful, easy to use and helpful function called password_hash. Use it.
  • You seem to be confused as to the point of OOP. In PHP, and many other languages, OOP isn't used to reduce the size of your code base (look at Java, or even C++). It's about making a sizable code base more manageable, more structured. Yes, when you first start writing OO code, you'll find yourself writing a lot more code than you were used to. The benefits are that, after a while, you'll find yourself re-using bits of code that you had written for another project. OOP enable (or at least facilitates) abstraction, separation of concerns and force developers to think more about what task should go where in the application. If you want to write OO code, don't go looking for ways to reduce the amount of code you write, look for ways to improve the overall structure of your project, and optimize what component has access to what functionality at any given time.

I'll be going into all of these issues in detail, each time updating this answer, but for now, I'd urge you to check out the links I provided here, and google some OOP terms like the SOLID principles

If you want to avoid lengthy code at all costs, then perhaps you should consider learning another language than PHP. Perl, for example, allows you to write obfuscated code a lot easier. Mind you, PHP has a couple of tricks up its sleeve, as this "Hello world" demonstrates (source):

<?=${[${[${[${[${[${[${[${[${${![]}.=[]}.=${![]}{!![]}]}.=${!![${[${[${[${[${[${[${[]}++]}
++]}++]}++]}++]}++]}++]}{![]+![]+![]}]}.=${[${[${[${[]}++]}++]}++]}{![]+![]}
.${![]}{![]+![]+![]}]}.=${[${![]}=${![]}{!![]}]}{!![${!![${!![${![]}++]}++]}++]}^
${!![${[${[${[]}++]}++]}++]};

Update 1
As you requested, some more details on the second issue I mentioned (about the dbConnectmethod being flawed). Your code, as it stands now expects the user to write something like:

$obj = new dbConfig();
$obj->host = '127.0.0.1';
$obj->username = 'user';
$obj->password = 'pass';
$obj->dab = 'dbname';
$obj->dbConnect();

But what if, because most devs are lazy, someone writes:

$db = new DbConfig();//classes should start with an UpperCase
//some code
someFunction($db);
//where someFunction looks like:
function someFunction(DbConfig $db)
{
    $db->dbConnect();//<== ERROR! host, user, pass... nothing is set
}

The instance could be created in a different file as the line that is calling dbConnect, so debugging this kind of code is hellish. You could re-write each piece of code that calls dbConnect to make sure all of the required properties have been set correctly, but what if they aren't? And what is "correct"? That's something the instantiating code should know, not the code that calls dbConnect. Luckily, you can use a constructor to ensure all parameters are known:

class DbConnect
{
    /**
     * @var string
     */
    protected $host = null;

    /**
     * @var string
     */
    protected $username = null;

    /**
     * @var string
     */
    protected $pass = null;//null for no pass

    /**
     * @var string
     */
    protected $dbName = null;

    /**
     * @var mysqli
     */
    protected $conn = null;

    public function __construct($host, $user, $pass = null, $db = null)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass
        $this->dbName = $db;
    }

}

Now, whenever an instance is created, the host and user must be passed to the constructor, if not, PHP will throw up a fatal error. So you'll have to use the class like so:

$db = new DbConnect('127.0.0.1', 'root', '', 'chatapp');

This reduces the users' code (where your class is being used), and makes the instances behave more predictably.

You may have noticed that I've changed the visibility from public to protected. That's because public properties can be reassigned on the go, without any validation on their new value whatsoever. That's dangerous. Instead, I suggest you add some getters and setters for the properties that you want to expose (like the database):

public function setDbName($name)
{
    if (!is_string($name))
    {//dbName MUST be a string, of course, so if it isn't, notify the user
        throw new InvalidArgumentException(
            sprintf(
                '%s expects name argument to be a string, instead saw "%s"',
                __METHOD__,
                gettype($name)
            )
        );
    }
    $this->dbName = $name;
    return $this;
}

Using this method, you can also check if the instance is currently holding an active db connection, clean up whatever needs to be cleaned up (closing cursors, freeing results, ...) and (re)connect or select the new db on that connection.
On the user side, using these setters is as simple as:

$instance->setDbName('foobar');
//but:
$instance->setDbName(array());
//InvalidArgumentException
//message: DbConnect::setDbName expects name argument to be a string, instead saw "array"

Given that your class clearly tries to abstract the nitty-gritty of the rather messy mysqli API away from the user (which I can understand), it's also important that the user needn't worry about closing the connection in time. When your instance of DbConnect goes, then so must the DB connection itself go. For that, a simple desctructor would do the job just fine:

public function __destruct()
{
    if ($this->conn instanceof mysqli)
        this->conn->close();//or mysqli_close($this->conn);
    $this->conn = null;//optional
}

Now you can rest assured that, in case someone writes this:

$db = new DbConnect('127.0.0.1', 'root');
$db->dbConnect();
//...code here
$db = null;//or unset($db), or $db just goes out of scope

The connection will be closed automatically. Naturally, for all of these changes to take effect, you'll have to refactor your dbConnect method somewhat, but that's something I'll try to cover in the next update.

shareimprove this answer
   
Yes, I was really confused of OOP. Thank you for your comment. Well to be honest, I wasn't aware of the real objective of OO code.I would love to hear more from you. for now can you explain 2nd point a bit more ? Thank you for your time. – RajeebTheGreat Dec 30 '14 at 11:47
   
@RajeebTheGreat: You're welcome. I will update this answer, and focus on your code a bit more. When I find the time (later today probably), I'll post an update explaining the 2nd point a bit more, and providing some suggestions as to how to approach things – Elias Van Ootegem Dec 30 '14 at 12:09
   
@RajeebTheGreat: Added the first of, probably, many updates just now, focusing mainly on the second issue I pointed out – Elias Van Ootegem Dec 30 '14 at 15:38


728x90


I'm not sure what's going wrong here. I was just following a tutorial online and these errors popped up.

I'm getting the following errors

Error

Notice: Undefined variable: db in C:\xampp\htdocs\wisconsindairyfarmers\admin\login.php on line 7

Fatal error: Call to a member function query() on null in C:\xampp\htdocs\wisconsindairyfarmers\admin\login.php on line 7

Code

<?php
$db = new mysqli('127.0.0.1', 'root', '', 'wisconsindairyfarmers');
?>

<?php
require '../db/connect.php';
require '../functions/general.php';

    function user_exists($username){
        //$username = sanitize($username);
        $result = $db->query("SELECT COUNT(UserId) FROM users WHERE UserName = '$username'");
        if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;
    }}

if(empty($_POST) === false){

    $username = $_POST['username'];
    $password = $_POST['password'];

    if(empty($username) === true || empty($password) === true){ 
        echo 'You need to enter a username and password';
    }
    else if(user_exists($username) === false) {
        echo 'We can\'t find that username.';
    }
}

?>
shareimprove this question
3 
Your $db variable is inside a function and thus out of scope from the code that defines it. Declare it global, or better, pass it as an argument to your function. See the PHP manual on scope – user1864610 Jun 23 '15 at 2:22 
   
I changed the variables, and the first error is fixed, but I'm still getting : Fatal error: Call to undefined function mysqli_result() – MPStimpson Jun 23 '15 at 2:32
   
I think that is because you are using OOP on the first part and procedural for the the results. – Rasclatt Jun 23 '15 at 2:38
   
I'm kind of new to php, how do I go about fixing that? – MPStimpson Jun 23 '15 at 2:41
   
I think that's because mysqli_result() is not a function. I'm really not clear what that piece of code is trying to do, but mysqli_result() doesn't exist in PHP. – user1864610 Jun 23 '15 at 2:41

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }
shareimprove this answer
   
I'm not getting any errors anymore, but I can't seem to get into the 'user_exists($username) === false' when I'm testing do you have any other wisdom to share with me today :) – MPStimpson Jun 23 '15 at 4:08
   
Yes, your SQL query will always return 1 row, with 1 field saying the amount of users equals to username. Change that to "SELECT * FROM users WHERE UserName = '$username'" and it will work – Juan Carlos Alvez Balbastro Jun 24 '15 at 17:41
   
I figured that out, but thank you very much! You've been very helpful! That's what I get for blindly following tutorials – MPStimpson Jun 26 '15 at 1:06


'WEB > jQuery' 카테고리의 다른 글

jQuery change() Method  (0) 2018.01.14
PHP array_push  (0) 2018.01.14
Fatal error: Call to a member function fetch_array() on a non-object  (0) 2018.01.14
달력 - 날짜입력기(Date Picker)  (0) 2018.01.14
javascript comma and uncomma  (0) 2018.01.14

+ Recent posts