PHP: is there difference between Index, Element, K

2019-04-29 12:33发布

问题:

When dealing with PHP arrays, I quite often here terms such as:

Array Key,

Array Index,

Array Element,

Array Value

Can someone, PLEASE , in simple terms explain what each of these basically means?

Is there any difference?... are they all referring to the same thing?

Where do you use which? and when?

Any clarification with some simple use case examples will be highly appreciated.

i.e: in an array like: array($a,$b,$c,$d=>$e) What will be What?

Thanks in advance.

回答1:

An array is a collection of Elements.
Every element has key & value. Key can be a integer(index) or a string.
In you case

array($a, $b, $c, $d=>$e)

can be rewritten as

array(0 => $a, 1 => $b, 2 => $c, $d => $e);  

Where 0, 1, 2, $d are the keys of the array.
You can refer 0, 1, 2 as a index for value $a,$b,$c respectively and $d is a key for $e.

.



回答2:

Key == Index, Element == Value



回答3:

That would be:

array(
    0  => $a, // index: 0, value : $a
    1  => $b, // index: 1, value : $b
    2  => $c, // index: 2, value : $c
    $d => $e  // index: $d, value : $e
)


回答4:

In my experience most PHP documentation uses the key => value configuration, while index: element is more common in JavaScript and jQuery.

PHP docs:

http://us2.php.net/manual/en/language.types.array.php

JavaScript Docs (Mozilla):

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

They both apply to the same concept where objects in an array have an index or key, and subsidiary objects, elements or values attached to that key.