Hi GOS,
the problem has been solved but, compared to the proposed example (which still created difficulties), with a modification to the code and to the database.
A text field has been added to the database in which to insert a value in case of absence of images while in the code the control is performed on the new field instead of the ‘gallery media’ field:

This because the previous code does not seem to detect the NULL value.
Any ideas on this?
In any case, thanks again and good evening.