Skip to content
PHP Logo

Can you store a loop in a variable in PHP?

In PHP, you cannot directly store a loop in a variable. However, you can achieve a similar result by storing the loop logic in a function and then assigning that function to a variable. This way, you can call the function whenever you need to execute the loop.

php
// Define a function containing the loop logic
$loopFunction = function() {
    for ($i = 0; $i < 5; $i++) {
        echo $i . " ";
    }
};

// Call the function to execute the loop
$loopFunction();