PHP is ksort() necessary if using array values only individually?

374 Views Asked by At

A simple question today!

I've ended up defining the values in my array non-sequentially, in other words 2 => 'marmosets' is defined before 0 => cats and 1 => dogs. It is my understanding is that the keys will assign properly (ie value marmosets will indeed be key 2 not key 0 even though it is defined first), but that my array will be 'out of order' such that a print_r() would output:

2 => marmosets
0 => cats
1 => dogs

And that if I want to put them in numerical order by key, ksort() will do that job.

(a) Is my understanding correct? (b) If I'm only using these values individually, and never need to output the list, is there any harm/impact in skipping the ksort() and leaving them "out of order"?

2

There are 2 best solutions below

0
Felk On BEST ANSWER

(a) Yes and (b) No.

a) PHP's arrays are ordered maps. The default order will stay insertion order until you change that, e.g. by sorting.

b) If you never do anything that relies on any order, e.g. just accessing data by keys, the order is irrelevant, so there's no harm.

0
samrap On

Printing the array will indeed print it in the order your created it with, whether those keys are numeric or associative. This can be proven simply by testing your example. There is no harm in skipping ksort if you do not rely on the actual order of the array. However, it does not hurt to use ksort either. Unless you are dealing with huge amounts of data, sorting the array once in your application will have no noticable effect on performance.