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

I’m afraid there is no function in WP core that will get number of unique categories based on given list of posts…

So let’s take a look at your code first… There are some problems in it…

  1. There is no need to use typical loop in here – it causes many operations in background (setting global variables and so on). It would be more efficient to use foreach instead.

  2. It can return incorrect results if there are multiple categories with the same name (and different parent for example).

And is there any more efficient way to do this? Yes, there is (especially, if there are many posts returned) – you can use custom SQL to obtain the categories count with only one query… Here’s how:

global $wp_query;
global $wpdb;
$post_ids = implode( ',', wp_list_pluck( $wp_query->posts, 'ID' ) );
$total_categories_in_search_results = $wpdb->get_var( "
    SELECT COUNT(DISTINCT tt.term_taxonomy_id) FROM
        {$wpdb->term_taxonomy} tt
        INNER JOIN {$wpdb->term_relationships} tr ON ( tt.term_taxonomy_id = tr.term_taxonomy_id )
    WHERE
        tt.taxonomy = 'category'
        AND tr.object_id IN ({$post_ids})
" );