What are some best practices for managing memory usage in PHP scripts to avoid memory exhaustion errors?

Memory exhaustion errors in PHP scripts can be avoided by implementing best practices such as limiting the amount of memory allocated for each script execution, optimizing code to reduce memory usage, and releasing memory when it is no longer needed. One way to manage memory usage is by using functions like `memory_get_peak_usage()` to track the peak memory usage during script execution and adjust accordingly.

// Limit memory usage for PHP script
ini_set('memory_limit', '128M');

// Track peak memory usage during script execution
$peak_memory_usage = memory_get_peak_usage();

// Release memory when it is no longer needed
unset($variable);