Trying to understand php code

You don’t escape input - you validate or sanitize input.

Escaping is for output when there is no way to keep the data separate from the code and the output can contain characters that could be misinterpreted as code. Escaping is always specific to the use being made of the data and so should be done last after all the rest of the processing.