Thanks for the answer
Changing the ways did not help ...
I found a pattern. The script work out fine if:
1. removal of the main image
2. the very first pictures from additional photo
3. removing all the additional photos.
The only problem with the removal of any photos, except for the first
Do you have any thoughts?
P.S. Please note that these problems are identified in the registered user. In administrative mode, everything works properly.