I'm wondering if all PHP arrays have to have key
s for their value
s? I don't think they do, and so my next question is, does the key
for each value
automatically become it's position in the array (0-based indexing), or else does the value
itself become the key
?
Perhaps the value simply doesn't have a key... curious, because I can't delete an element from an array inside a foreach
loop if it doesn't have a key.
I'm wondering if all PHP arrays have to have keys for their values?
Yes, they do.
Does the key for each value automatically become it's position in the array (0-based indexing)
Yes. If you do not explicitly specify a key value, then it's corresponding position will be used (0-based indices).
I can't delete an element from an array inside a foreach loop if it doesn't have a key.
You don't always need a key to operate with arrays. Also, foreach
construct allows you to use the keys inside the array: foreach ($iterable as $key => $value)
.
I'm wondering if all PHP arrays have to have keys for their values?
Yes. From the documentation:
Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
Therefore, all elements of an array must have a key.
does the key for each value automatically become it's position in the array (0-based indexing)
Almost correct. If a key is not specified for an element, the key will be 1 + the key of the previous element, with the key of the first element being 0.
I can't delete an element from an array inside a foreach loop if it doesn't have a key.
There is actually foreach
syntax that exposes the key in addition to the value. From the documentation:
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement
An example using the latter foreach
syntax for deleting array elements is as follows:
// Remove elements from the array that are less than 10
foreach ($array as $key => $value) {
if ($value < 10) {
unset($array[$key]);
}
}
Yes the key of each value is 0-based index. you can create an array and var_dump() it to see the keys. http://www.php.net/manual/en/language.types.array.php