How can I pass a PHP string variable to a JavaScript function?

Solution 1:

PHP’s alternative syntax is convenient for mixing loops with HTML, making templates easier to read:


<?php for ($floorNow = 1; $floorNow <= 5; $floorNow++) : 
      $floorDiv = 'floorData' . $floorNow;
?>
    <div class="FloorH">
        &nbsp;First Floor
        <button value="<?= htmlspecialchars($floorDiv) ?>" 
                onclick="changeBG(this.value, '#F0F')">
            Magenta
        </button>
    </div>
    <div id="<?= $floorDiv ?>"></div>
<?php endfor; ?>

Explanation:

for (…): … endfor; is the alternative syntax for loops, ideal for HTML templates.

$floorDiv dynamically generates unique IDs for each floor.

htmlspecialchars() ensures the ID is safe to use in HTML attributes.

Each button calls changeBG() with the corresponding floor ID and a color.

✅ This syntax keeps your PHP and HTML clean and readable.

Solution 2:

You can use a while loop to dynamically generate floors and buttons in PHP:


<?php
$floorCount = 5;
$floorNow = 1;

while ($floorNow <= $floorCount) {
    $floorDiv = 'floorData' . $floorNow; // Unique ID for each floor

    echo '<div class="FloorH">
            &nbsp;First Floor 
            <button onclick="changeBG(\'' . $floorDiv . '\', \'#F0F\');">
                Magenta
            </button>
          </div>';

    echo '<div id="' . $floorDiv . '"></div>';

    $floorNow++;
}
?>

Explanation:

$floorNow counts from 1 up to $floorCount.

$floorDiv dynamically generates a unique ID for each floor div.

onclick=”changeBG(…)” passes the div ID and color to a JavaScript function.

echo outputs the HTML directly inside the PHP loop.

✅ This method uses the classic while loop syntax and works perfectly for dynamically generating repeated HTML elements.