Junior
What types of arrays exist in PHP?
sobes.tech AI
Answer from AI
In PHP, arrays are maps that associate keys with values. There is essentially only one type of "array," but its usage allows for simulating various data structures.
The main types of usage, often incorrectly called "types":
- Indexed arrays (strictly speaking, arrays with numeric, sequential keys starting from 0).
- Associative arrays (arrays with string keys or arbitrary numbers).
Examples:
// Indexed array
$indexedArray = ['apple', 'banana', 'cherry'];
// Access by index
echo $indexedArray[0]; // Output: apple
// Associative array
$associativeArray = [
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
];
// Access by key
echo $associativeArray['name']; // Output: John Doe
It is important to understand that PHP does not distinguish these "types" internally as different data structures, unlike some other languages. PHP array is a universal structure capable of containing key-value pairs, where keys can be integers or strings, and values can be any data type.
You can mix key types in a single array:
// Mixed array
$mixedArray = [
0 => 'first',
'second' => 'second',
3 => 'third'
];
echo $mixedArray[0]; // Output: first
echo $mixedArray['second']; // Output: second
echo $mixedArray[3]; // Output: third