How can memory limits be effectively managed and tested in PHP scripts to avoid exhaustion errors?

Memory limits in PHP scripts can be effectively managed and tested by setting the memory_limit directive in the php.ini file or using the ini_set() function within the script itself. To avoid exhaustion errors, it's important to monitor memory usage, optimize code to reduce memory consumption, and handle large data sets efficiently.

// Set memory limit in PHP script
ini_set('memory_limit', '256M');

// Check memory usage
$memoryUsage = memory_get_usage();
echo "Memory Usage: " . $memoryUsage . " bytes";