In PHP, do associative array indexes need to follow that same rules and variable names (can't start with a number, etc.) I am looking for both working and philosophical answers to this question.
There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables.
An array in PHP is actually an ordered map. So yes, they are always ordered.
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
From the manual:
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.
In their example, using something like $array["08"]
is perfectly acceptable and will count as a string, though as you ptobably know, it's highly not recommended. Always name your variables logically.
no, associative arrays can have numerical keys. any valid string can be an index. as far as code styles and clarity, the important thing is that is the keys make sense and are readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With