9

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.

Universal Grasp
  • 1,835
  • 3
  • 20
  • 29

4 Answers4

5

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.

.

Tarun
  • 3,162
  • 3
  • 29
  • 45
  • What do you mean by `value.Key`? – Universal Grasp Nov 23 '13 at 09:27
  • So, should i want to check if `$a` or `$b` or `$c` exists or are put there what `function` should used is there any `function` in `PHP` to check if an `Index` exists or is available? – Universal Grasp Nov 23 '13 at 09:31
  • Thanks again. I check the site but there is not example with an `index` `array`. All examples have `key=>value` setup. how do you implement the same in a basic `index` `array` like `array($a,$b,$c)` ? – Universal Grasp Nov 23 '13 at 09:39
  • 1
    array_key_exists("0",array($a,$b,$c)),array_key_exists("1",array($a,$b,$c)),array_key_exists("2",array($a,$b,$c)) or you can use isset – Tarun Nov 23 '13 at 09:41
  • Managed to go through... **Yes it worked** and Thank you very much for the explanation. Am accepting your answer – Universal Grasp Nov 23 '13 at 09:46
1

Key == Index, Element == Value

enumag
  • 830
  • 11
  • 21
0

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
)
Eduardo Casas
  • 578
  • 4
  • 11
0

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.

Tim Ogilvy
  • 1,923
  • 1
  • 24
  • 36