Sushant Kochar
Sushant Kochar

Reputation: 155

automatic sorting of numeric keys in array php

I have an array where I insert values with numeric keys associated with them. My problem is that when I insert a value with key less than a key which has been inserted before it comes after the larger key in the array i.e, it is the next element not the previous one(but the key is smaller). I don't want to apply sorting as I don't have much time limit and data is large. Later I need to search the array for a particular key and value pair. Therefore I can't use array pad to initialize the array(length of array is 100000). Because if I do it, the search would be really slow. I just want the key value pair (which I insert) to be in array but I wish that a key with lesser numeric value should automatically become previous element to a key with greater numeric value. For example:

$a[0]=1;
$a[25]=2;
$a[12]=3;

Here $a[12] should be the second element of the array but as I use foreach to excess every element, it comes out to be the third element.

Upvotes: 0

Views: 2993

Answers (1)

user554546
user554546

Reputation:

You can't get sorting for free. Initialize the array with a simple foreach loop. Either that or bite the bullet and either a) sort at the end or b) do a sort after each element is inserted.

Upvotes: 4

Related Questions