Displaying elements from an array sequentially

Hi. I’d like to receive an image from an array, sequentially, after I click a button.
So when I first click on a button an image (Axajafied) will appear on my page. When I hit the button again I’d like the next image in the array to appear, and so on. I have the javascript / Ajax part working correctly. However my PHP code (where the request is received) is where I need to implement this. Currently I have a technique where I shuffle the array and choose the last element of the array. See attached code.
Thanks

// MAKE AN ARRAY OF THE JPG IMAGE FILE NAMES
$b = array();
while (($filename = readdir($dh)) !== FALSE)
{
// CHOOSE ONLY JPG IMAGES
$file_ext = strtoupper(end(explode(‘.’, $filename)));
if ($file_ext != ‘JPG’) continue;

    $b[] = $filename;
	
}
closedir($dh); 

// MAKE AN ARRAY OF THE JPG IMAGE FILE NAMES

   

// WITH ALL FILE NAMES IN AN ARRAY, RANDOMIZE THE LIST AND CHOOSE ONE
shuffle($b);
$banner_name  = array_pop($b);
$banner_url   = $my_dir . $banner_name;

}

In order for this to work you’d need to maintain a state between the javascript side of things and the PHP side of things. You could do this, but I think it’s more complicated than it needs to be.
What I would do is create the array once in PHP and send the complete array over to javascript, on the first time the button is pressed.
From that point on javascript can figure out which element it needs to show by just iterating the array.
This has the added advantage that you only need one http request to fetch the complete array, instead of n http request for n clicks, thus speeding up the application (considering an HTTP request takes somewhere between 7 and 100ms, depending on the server of course).