0

This is my array:

array(
99 => 100,
53 => 200,
29 => 300
)

I would like to add a new item at index 2 like this:

array(
99 => 100,
53 => 200,
36 => 'new',
29 => 300
)

I only found a solution to add a new item without own key, have anyone an idea?

Alexander G.
  • 333
  • 1
  • 4
  • 15
  • what's so difficult about `$foo[36] = 'new'`? – Marc B Jan 13 '15 at 15:07
  • 5
    possible duplicate of [Insert new item in array on any position in PHP](http://stackoverflow.com/questions/3797239/insert-new-item-in-array-on-any-position-in-php) – Shaiful Islam Jan 13 '15 at 15:08
  • so you want to insert to a specific index of an array? possible duplication of http://stackoverflow.com/questions/3353745/how-to-insert-element-into-array-to-specific-position – Todd Matthews Jan 13 '15 at 15:12

2 Answers2

0
$table[36] = 'new'

In case of duplicate entry, you should reinsert the entry with a new key before.

$table[] = $table[36];
$table[36] = 'new';
Macbernie
  • 1,135
  • 4
  • 19
  • 41
0

If the array is sorted and it looks like this.

You can add the new element:

$array[36] = 'new';

and sort it afterwards:

krsort($array);
knobli
  • 587
  • 6
  • 16