使用backstretch时从目录中获取图像和文件名

I'm a php noob as you may guess.

What I want to do: fetch images from a directory and display them in backstretch while simultaneously fetching the filename and displaying that in a header.

The code below fetches the images randomly, I don't need it to be random, in fact it would be better if I could control the order of the images and display the corresponding filename.

Fetch images from directory and display them randomly:

<script>
    $.backstretch([<?=GetRandomImagesFromDir('backgrounds/')?>], {
        fade: 750,
        duration: 4000
    });
    
</script>
<?php
//Start Session
session_start();


function GetRandomImagesFromDir( $image_dir ) {
//Create image array
$images = glob($image_dir . '*.jpg');


//Get first image
    //Get one random image from array
    $rand_key = array_rand($images, 1);

    //Same image as before?
    if ( $rand_key == $_SESSION['last_image'] ) {
        if ( $rand_key > 1 ) {
            $rand_key--;
        } else {
            $rand_key++;
        }
    }

    //Save Key to Session
    $_SESSION['last_image'] = $rand_key;

    //Save image to var
    $first_image = $images[ $rand_key ];


//Get next images
    //Remove first-image from array
    unset( $images[ $rand_key ] );

    //Shuffle
    shuffle( $images );

    //Add first image
    $images[] = $first_image;

    //Reverse array
    $images = array_reverse($images);


//Array to string
    $return_str = implode('","', $images);
    $return_str = '"'.$return_str.'"';


//Return string
return $return_str;
}
?>

As this function, GetRandomImagesFromDir, is called at the bottom of the php page and the header tag that I want the filename to be displayed is above this, I'm a bit stumped.

The code below is working for pulling in a list of the filenames, but I only want to display the one relevant to the image. Hope you can help!

<?php
  $files = glob("backgrounds/*.*");

  for ($i=0; $i<count($files); $i++) {
  $image = $files[$i];
  $name = basename($files[$i], ".jpg"); 
  echo str_replace('-', ' ', basename($name, ".jpg")) ."<br />";      
  }
?>   

</div>