How do I get the total number of categories in a list of search results?

I want to display the total count of categories in a set of search results.

For example, “10 posts found in 3 categories.” (Assuming that each post has only 1 category.)

Right now, my solution is to run through the loop, capture each post’s category in an array, then count the unique values:

<?php
    $categories_in_search_results = array();
    if (have_posts()) : 
        while (have_posts()) : the_post();
            array_push($categories_in_search_results, get_the_category()[0]->name);
        endwhile; 
    endif; 
    wp_reset_postdata();
    $total_categories_in_search_results = count(array_unique($categories_in_search_results));
?>

Does WordPress provide a cleaner way to do this or is there a more efficient approach?

Solutions Collecting From Web of "How do I get the total number of categories in a list of search results?"