How to pass a variable into an add_filter() function?

You could use an anonymous function and pass the variable to it with use.

$updatedLanguage = $languageArray[$pageLanguage] ?? '';
if ( $updatedLanguage ) {
    add_filter('locale', function($locale) use ($updatedLanguage) {
        return $updatedLanguage;
    });
}

If you’re changing the locale at runtime, then you may want to look here Change locale manually at runtime?, where it is noted that the change could have a performance impact. Also, you may need to do the change early enough in the WP loading sequence so that the correct translation file gets loaded – if it something that you need.

error code: 523