SoLoGHoST
SoLoGHoST

Reputation: 2689

Alternative to array_shift function

Ok, I need keys to be preserved within this array and I just want to shift the 1st element from this array. Actually I know that the first key of this array will always be 1 when I do this:

// Sort it by 1st group and 1st layout.
ksort($disabled_sections);
    foreach($disabled_sections as &$grouplayout)
        ksort($grouplayout);

Basically I'd rather not have to ksort it in order to grab this array where the key = 1. And, honestly, I'm not a big fan of array_shift, it just takes to long IMO. Is there another way. Perhaps a way to extract the entire array where $disabled_sections[1] is found without having to do a foreach and sorting it, and array_shift. I just wanna add $disabled[1] to a different array and remove it from this array altogether. While keeping both arrays keys structured the way they are. Technically, it would even be fine to do this:

$array = array();
$array = $disabled_sections[1];

But it needs to remove it from $disabled_sections. Can I use something like this approach...

$array = array();
$array = $disabled_sections[1];
$disabled_sections -= $disabled_sections[1];

Is something like the above even possible??

Thanks.

Upvotes: 4

Views: 9207

Answers (2)

Erik
Erik

Reputation: 20722

While there's no -= operator in that fashion, you can use unset to remove that element from an array:

unset(disabled_sections[1]);

But that's just implementing your own version of shift. I do wonder under what situation you're finding array_shift() to be 'slow' and how you're testing said slowness.

Numeric arrays are sorted numerical by default - no ksort is required. Maybe you should try something like

while($array = array_shift($group_of_arrays)) {

  // ... do stuff
}

If you are not concerned about the order in which you pull elements out of the array, you can use "array_pop" instead of "array_shift". Since "array_pop" takes the elements off of the end of the array, no reindexing is required and performance increases dramatically. In testing with an array of about 80,000 entries I am seeing about a 90% decrease in processing time with "array_pop".

Upvotes: 2

pinkgothic
pinkgothic

Reputation: 6179

Despite there being an accepted answer to this; in case someone else stumbles across this, a way to unset the first element of an array (regardless of its key, or the order of its keys) without using array_shift is:

reset($array); // sets internal array pointer to start
unset($array[key($array)]); // key() returns key of current array element

Though I'm fairly convinced that's what array_shift does internally (so I imagine there would be no performance gain to this), excepting an additional return of the value retrieved:

$element = reset($array); // also returns element
unset($array[key($array)]);
return $element;

Just for completion's sake.

Upvotes: 6

Related Questions