I came across a requirement to cache a database result and needed a cached object to work like PHP’s mysqli_fetch_assoc()
— where you can use it in a while loop and it iterates through the array until it gets to the end.
I know many developers tend to use some kind of database abstraction so it’s not often we deal with the lower level database functions. Regardless, I couldn't find an example to do what I was after so here is one.
Here’s the code followed by an explanation:
<pre><?php
// The function
function fetchArray(&$array) {
$current = current($array);
if ($current !== false) {
next($array);
}
return $current;
}
// Normal array example
$array = ['Foo', 'Bar' , 'Foo Bar'];
while ($row = fetchArray($array)) {
echo $row . PHP_EOL;
}
echo PHP_EOL;
// Associative array example
$assoc = [['foo' => 'Foo 1'], ['foo' => 'Foo 2'], ['foo' => 'Foo 3']];
while ($row = fetchArray($assoc)) {
echo $row['foo'] . PHP_EOL;
}
// Output:
// Foo
// Bar
// Foo Bar
//
// Foo 1
// Foo 2
// Foo 3
?></pre>
Arrays in PHP have a pointer that points to the "current" element (by default the first element in the array). A while loop will execute until the condition is false.
The function works by using current()
to check if the pointer is already at the end of the array. If it isn’t, it moves the pointer on to the next one with next()
. The current array element is then returned. current()
returns false
once the pointer goes past the last element so this naturally causes the while loop to stop.
Note that once you have called this function the array pointer is at the end of the array. If you wish to run it again you need to call reset()
on the array else nothing will happen when you call the function — because it will return false on the first iteration.