0

I tried with array_push(), but I get fatal error.

function get_data($table, $id = '', $condition){

   if($id != '')
     array_push( " WHERE `id` = '".$id."' ", $condition );

   ...
}

The question is, how to add a value (in my case a string) to the start of an array?

Reteras Remus
  • 923
  • 5
  • 19
  • 34

3 Answers3

8

array_unshift() is the function you are looking for!

array_unshift — Prepend one or more elements to the beginning of an array

$arr = array(1,2,3);
print_r($arr);

/*
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)   
*/
array_unshift($arr,0);
print_r($arr);

/*
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
)   
*/
Lix
  • 47,311
  • 12
  • 103
  • 131
  • 1
    Note that with array_unshift, the arguments will need reversed from what you have (just as for array_push) – Chris Trahey Aug 26 '12 at 21:29
  • 1
    it is in regard to the fact that the OP has the arguments in reverse order (which is the reason for the Fatal error); just want OP to notice that argument order matters :-) – Chris Trahey Aug 26 '12 at 21:33
4

The fatal error is because you have the arguments in reverse order:

function get_data($table, $id = '', $condition){

   if($id != '')
     array_push($condition, " WHERE `id` = '".$id."' " );

   ...
}

if $condition is an array, this will not give a fatal error, but it will place the item at the end of the array. As mentioned in other answers, array_unshift is the function to prepend an item.

Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
0

array_unshift should do the trick

PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
  • I kind of expected a higher quality in 2012. https://stackoverflow.com/questions/1739706/how-to-insert-an-item-at-the-beginning-of-an-array-in-php/1739716#comment120862746_1739716 – mickmackusa Jul 15 '21 at 03:58