How Can I Get Information From An Array From An ACF Image Field In WP?

I am very new to WP so this may seem like a very simple question. I am trying to provide a background image url via css class and advanced custom fields. I want to do it this ways so I can keep my class clean and dry. The image is stored in WP admin as a custom field image. Here is my hero template code:

if (have_posts()) : while (have_posts()) : the_post();
        $hero_img = get_field('hero_image');

<h3>ACF Field Data: <?php the_field('hero_image');?></h3> // just to see what it is

        <section class="panel--hero panel--bg-image" <?php $hero_img ? print 'style="--background-image: url("hero_img[5]");"' : ''; ?>>
            <div class="panel__content">

                <div class="container container__grid page-heading">
                    <div class="container__col">
                        <h2 class="page-title center--flex text-white"><?php the_title() ?></h2>


And the scss:

 &--bg-image {
      position: relative;
      height: 50vh;
      &::after {
        background-image: var(--background-image);
        background-position: center center;
        background-repeat: no-repeat;
        background-size: cover;
        bottom: 0;
        content: '';
        display: block;
        opacity: var(--opacity);
        left: 0;
        right: 0;
        position: absolute;
        top: 0;
        z-index: -1;

No image is showing up. The absolute path is the fifth item in that array, and it's not coming through. In JS I would normally loop through it, but I thought I already did that using the 'if/while' loop above my variable declaration. Do I need to loop the $hero_img variable now too? And if so, that is the most conventional way to do this in WP/PHP? Is forEach an option? Perhaps I'm not clear on that data is available just by running the if/while loop. Any help would be much appreciated!! Thanks.



Option 1 - Use the array key

Assuming you are using ACF and the field is set up to return the "Image Array", you can get the image url using the array key url, i.e.:

$hero_img_url = $hero_img['url'];

Option 2 - Only return the URL from ACF

If you will only ever want to get the URL of the image, you can change the return format to "Image URL" in the ACF setup of the field. Then get_field returns only the url and you can get it like you are already, e.g.:

$hero_img_url = get_field('hero_image');

Additional Notes

  1. when you're using an associative array (i.e. an array with keys), then the position is irrelevant so you don't try to get the 5th element, for example. You just use the key to get the value directly.
  2. If you are not sure what is in an array or what the keys are, you can use var_dump($hero_img); to output to the screen exactly what keys and values it has.