In a foreach loop, how can I add a meta value if it doesn’t exist?

My problem was just trying to do too much in at once. In the main foreach loop:

if (!empty($names)) {
  foreach ($names as $val) {

     // Get the pdf's unique_id if it's in the db already
     $unique_id = get_post_meta($val, $ticketidmeta, false);

     // If the unique_id isn't there, create it
     if ( empty( $unique_id ) ) {
        $unique_id = uniqid( '', true );
        // uniqid() with more_entropy results in something like '59dfc07503b009.71316471'
        $unique_id = str_replace( '.', '', $unique_id );

        $unique_id = sanitize_file_name( $unique_id );

        add_post_meta( $val, $ticketidmeta, $unique_id, true );
     }

     // Use that unique id to make the ticket path
     $ticketurl = sprintf( $base_ticket_path . sprintf(implode($unique_id)));

     // Add each unique id to an array
     $uniqueIDs[] = $ticketurl;
   }
}
$attendees_data = sprintf(implode($uniqueIDs));

In my original question, I was trying to set the final array at the first statement of the foreach, and check if the metadata was there, and assign that metadata to the value in the final array.

Instead, now for each $val we first try to get the post meta data, then if it doesn’t exist we create it, then we do some structuring of that metadata, then we assign it to the final array variable.

As you can tell from the last line there’s more work to do on this project, but thank you for everyone who tried to help!