Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - associative array index naming conventions

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.

like image 530
user897363 Avatar asked Aug 16 '11 20:08

user897363


People also ask

Are PHP arrays associative or integer indexed?

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.

Is PHP associative array ordered?

An array in PHP is actually an ordered map. So yes, they are always ordered.

What is Array_keys () used for?

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.


2 Answers

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.

like image 61
Madara's Ghost Avatar answered Oct 13 '22 14:10

Madara's Ghost


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.

like image 39
GSto Avatar answered Oct 13 '22 14:10

GSto