Prevent underscores from removing text?
I'm struggling to understand what that code is trying to do; I'm assuming your end goal is to render either this:

&lt;div class="gcse-searchresults-only"&gt;&lt;/div&gt;


Or this, if the condition passes:

&lt;div class="gcse-searchresults-only" data-as_sitesearch="https://www.example.com/drupal8_gcse/"&gt;&lt;/div&gt;


But I don't see how the code sample would ever to get to even the result in your question. There's no mention of a &lt;div&gt;, and if $block contains the opening &lt;div..., then you've forgotten to close the opening tag and provide a closing tag after concat'ing the attribute string.

To make the whole thing easier (and a bit cleaner), you can use html_tag instead:

$form['search']['results'] = [
  '#type' =&gt; 'html_tag',
  '#tag' =&gt; 'div',
  '#attributes' =&gt; ['class' =&gt; ['gcse-searchresults-only']],
  '#value' =&gt; '',
];

if (array_key_exists('search_broadness', $get_results) &amp;&amp; $get_results['search_broadness'] == 'narrow') {
  $form['search']['results']['#attributes']['data-as_sitesearch'] = $gcse_narrow_search_query;
}