Are there any best practices for managing memory usage in PHP to avoid memory exhaustion errors?

Memory exhaustion errors in PHP can occur when a script uses more memory than the limit set in the php.ini file. To avoid these errors, it's important to optimize memory usage by freeing up memory when it's no longer needed. This can be done by unsetting variables, closing database connections, and using memory-efficient data structures.

// Example code to manage memory usage in PHP
// Unset variables when they are no longer needed
$largeArray = range(1, 1000000);
// Process $largeArray
unset($largeArray);

// Close database connections when done
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// Use $pdo
$pdo = null;

// Use memory-efficient data structures
$smallArray = [1, 2, 3, 4, 5];
// Process $smallArray