phparraysksort

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


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"?


Solution

  • (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.