Why doesn’t add_filter have the option to include a callback for each run?

There’s no reason to have this feature. If this is a problem you’re having then you’re using filters incorrectly.

Firstly, $collection is right there for you to check however you need to. If you need to see what the filtered collection contains, then just check the $collection variable passed to your callback. You don’t need any other functionality.

But you shouldn’t even need to do that. If you’re using a filter with add_filter(), then it’s your responsibility to know what types of values will be passed to the filter callback, and what value is expected at the other end, and it’s the responsibility of whoever implements the filter with apply_filters() to document what these expectations are.

For example, if a developer (or yourself) provides the filter my_collection for you to add your own strings to a list of strings, then under no circumstances should you be adding anything other than a string, and you must return an array, because all other users of this filter and the return value expect an array of strings.

Filters are an API, and they should have defined and documented expectations for what goes in and out of them. Anything that deviates from this should throw an error.

In your example:

$collection = apply_filters( 'my_collection', [] );
$string = '';
foreach( $collection as $collection_item ) {
    $string += $collection_item;
}

If $collection is not an array of strings, then the filter has been used incorrectly and an error is the expected behaviour. If you provide this filter in your theme or plugin for other developers to use then it’s important to document what is expected so that developers don’t make this error.

Let’s take a real example. The post_class filter is a core WordPress filter for adding classes to a post. The filtered value is defined in the documentation like this:

$classes

(string[]) An array of post class names.

That means that your callback function should expect that $classes is an array of strings, and that your callback must also return an array of strings. Anything else will break. There’s no reason to check what values have been added to $classes because it should only even be an array of strings.

tech