How can the memory usage of a PHP script be monitored and optimized to prevent exhausting the memory limit?

To monitor and optimize memory usage in a PHP script, you can use functions like memory_get_peak_usage() to track the peak memory usage during script execution. By identifying memory-intensive operations or variables, you can optimize code to reduce memory consumption and prevent hitting the memory limit.

// Monitor memory usage
$memoryUsage = memory_get_peak_usage(true);
echo "Peak memory usage: " . round($memoryUsage / (1024 * 1024), 2) . " MB";

// Optimize memory usage
// Example: Unset large arrays or objects after use
unset($largeArray);