18
array_unshift ($ids,$product_id => $catalog_tag);

if i put

array($product_id => $catalog_tag) 

would work but wont add $product_id as key.. I want to add it at the start

bcosca
  • 17,371
  • 5
  • 40
  • 51
GorillaApe
  • 3,611
  • 10
  • 63
  • 106
  • See [this](https://stackoverflow.com/a/11276338/2577705) answer. It refers to moving an already existing element to the beginning of the array, but it would also have the desired result if it doesn't exist. – craned Dec 08 '15 at 19:25

2 Answers2

44

Use array_reverse to reverse the array and then push the element to end of array using array_push and then reverse the array again. You will have the new element at beginning of the array.

or

$arrayone=array("newkey"=>"newvalue") + $arrayone; 
pableiros
  • 14,932
  • 12
  • 99
  • 105
Hacker
  • 7,798
  • 19
  • 84
  • 154
13

This code takes your array noting that it's using integer keys for your array so these will always be the array order, so we convert them to string keys and this prevents the key's acting as the order of the array. we then create the a new array with your value and append all values from your existing array to the end.

note that the product ID is converted to a string again to prevent the integer key from ordering the array.

$ids = array(0 => "bla bla", 1 => "bla bla", 2 => "bla bla", 3 => "bla bla")
foreach($ids as $key => $val){
    $key = "$key";
}
unset(current($ids));
$ids = array_merge(array("$product_id" => $catalog_tag), $ids);
Barkermn01
  • 6,781
  • 33
  • 83