If it's not happening every time the script runs, then my guess is:
- Running out of memory. (Unlikely looking at your code)
- Reaching maximum connections on the server where your file is hosted. (Your host should have some tool that you can use to get stats)
- Your PHP script is deployed on more than one servers, running behind a load balancer, and one of the servers has a corrupt version of your PHP file, or a corrupt PHP installation, or a faulty web-server(or web-server config). Whenever client request ends up on that corrupt server, you get the 500.