Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach loop takes array elements out of numeric order?

Tags:

arrays

php

I have an array I am building like this:

foreach($items as $item) {
    $this->_array[(int)$item->getPosition()] = $item;
}

When I then run through that array to output it, I expect this:

array (
    [0] => item0,
    [1] => item1,
    [2] => item2,
    [3] => item3,
)

But I get this:

array (
    [3] => item3,
    [0] => item0,
    [2] => item2,
    [1] => item1,
)

Which I can only assume is the order the keys were set in. Why aren't they coming out in order?

Is there a way to force the array to order by keys in numeric order?

like image 745
Daniel Bingham Avatar asked Feb 20 '26 06:02

Daniel Bingham


1 Answers

Just ksort() the array first.

like image 162
Explosion Pills Avatar answered Feb 23 '26 08:02

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!