Junior — Middle
What data structures allow very fast access to elements by key or index?
sobes.tech AI
Answer from AI
In PHP, the following data structures are used for very fast access to elements by key or index:
- Arrays (array): In PHP, arrays are implemented as hash tables, which provides amortized constant time access to an element by key (associative or numeric) close to O(1).
Example:
$arr = [
'key1' => 'value1',
'key2' => 'value2',
0 => 'zero',
1 => 'one'
];
echo $arr['key1']; // value1
echo $arr[0]; // zero
- SplFixedArray: If you need a fixed-size array with numeric indices and more efficient memory usage, you can use the
SplFixedArrayclass. Access by index is very fast.
$array = new SplFixedArray(10);
$array[0] = 'first';
echo $array[0]; // first
Thus, for quick access by key or index, PHP typically uses standard arrays, which are already optimized for such operations.