Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: What is the real meaning of an index in an indexed array?

Say, we make an array like this:

$arr = Array
(
            2 => 'c',
            1 => 'b',
            0 => 'a'
);

When you pass it to array_pop():

array_pop($arr);

And the "last" element would be poped off, which has the index of zero!!

print_r($arr);

Result:

Array
(
    [2] => c
    [1] => b
)   

So, what's the purpose of index? Isn't it just a different way of saying "numeric keys of associative arrays"?

Is it only PHP dose so, or all the languages treat arrays like this?

like image 966
Kevin Avatar asked Feb 12 '23 05:02

Kevin


2 Answers

Not all languages do this, but PHP does, because PHP is a little weird. It implements arrays more or less like dictionaries. PHP does offer some functions like ksort though, which let you sort the array by key.

And that's what this is: a key. An array has indexes as well, so what you got, is an array where item 2 has key 0. And that's where the confusion starts continues.

PHP: a fractal of bad design has a whole chapter about arrays. Interesting reading material. :)

like image 56
GolezTrol Avatar answered Feb 15 '23 09:02

GolezTrol


The reason for this behavior is because arrays in PHP are actually unordered maps.

Because of this, don't think of accessing the arrays in terms of indexes, think of it in terms of keys. Keys can be numbers and they can be strings, but the result is the same; you're still using a map, not a true "array".

Once you accept that fact, you'll understand why PHP includes functions like ksort() for sorting an array by keys and why array_pop() doesn't always remove the highest key value.

like image 34
Mr. Llama Avatar answered Feb 15 '23 09:02

Mr. Llama