How get you get element key
and value
of an at the n
position array at a particular position without loop.
Imagine
$postion = 3; // get array at 3rd position
$array = array(
"A" => "Four",
"B" => "twp",
"C" => "three",
"D" => "Four",
"E" => "Five",
"F" => "Four");
$keys = array_keys($array);
$value = array_values($array);
echo implode(array_slice($keys, $postion, 1)), PHP_EOL; // Key at 3rd posstion
echo implode(array_slice($value, $postion, 1)), PHP_EOL; // Value at n position
Output
D
Four
Issues With the method is
- Multiple Duplication of the array resulting higher memory usage
Why not use loop
- You have to get multiple position multiple times .. looping large data set not efficient either
Why not use a Database
- Yes working with memory based database like Redis can make life easier but am particular array optimisation
Why not use SplFixedArray
This would have been solution but i the follow weer because am not using positive keys ( I really this is nor fair on php part)
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'array must contain only positive integer keys'
What do you mean by large data set :
- Actually i stumble on this issue when trying to as this question Managing mega Arrays in PHP so am looking at
1e6
or1e7
with512M memory limit
Am sure something like fseek
for array would do the trick .. but not sure if that exists