What are the common pitfalls when using PHP functions within loops to generate dynamic content, and how can these be avoided for optimal performance?

Using PHP functions within loops can lead to performance issues due to the function being called multiple times unnecessarily. To avoid this, it's recommended to store the result of the function outside of the loop and then use that value within the loop instead.

// Example of storing the result of a function outside of a loop for optimal performance

// Function to generate dynamic content
function generateContent($value) {
    return "Dynamic content for value: $value";
}

// Storing the result of the function outside of the loop
$result = generateContent($someValue);

// Loop to use the stored result
for ($i = 0; $i < 10; $i++) {
    echo $result;
}