Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert at start of array a key-value pair in php

Tags:

php

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

like image 885
GorillaApe Avatar asked Nov 23 '10 10:11

GorillaApe


People also ask

How do you insert an item at the beginning of an array in PHP?

The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array. Tip: You can add one value, or as many as you like. Note: Numeric keys will start at 0 and increase by 1.

How do you add a key value pair to an array?

To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

How do you insert an element into an array at a specific index PHP?

A simple solution to insert an item at a specific position in an array is using the array_slice() function. The idea is to extract a slice of the array using array_slice() function and then recombine the parts using the array_merge() function.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


1 Answers

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; 
like image 149
Hacker Avatar answered Oct 07 '22 23:10

Hacker