phphtmlsuperglobals

Superglobal GET using PHP


I am new to php and I couldn't find the answer on stack. I am experimenting and trying to figure out how I can use the superglobal GET to display an image and also change the *count depending on how the user modifies it in the URL.

I would like to change the Beach image count times.

So the URL would look something like: website.com/table?beach_image=2&count=4

and would display the beach image #2, 4 times: bathing suit

<?php
$beach = ['sunglasses.jpg','suncreen.jpg','bathing-suit.jpg','hat.jpg'];
$count = 1;

    $beach_image = filter_input(INPUT_GET,"beach_image");
?>

for my html:

<table>
    <tr>
        <th>Beach Image</th>
        <th>Beach</th>
    </tr>
    <tr>
        <td>0</td>
        <td>Sunglasses</td>
    </tr>
    <tr>
        <td>1</td>
        <td>Sunscreen</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Bathing Suit</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Hat</td>
    </tr>
</table>
<div>
    <img src="images/<?= $beach[$beach_image]?>">
</div>

Solution

  • You can do it like below

    <?php
    $beach = ['sunglasses.jpg','suncreen.jpg','bathing-suit.jpg','hat.jpg'];
    $keysArr = array_fill(0,count($beach),0);//array_combine(array_keys($beach),array_fill(0,count($beach),0)); 
    
    $beach_image = filter_input(INPUT_GET,"beach_image");
    $count = filter_input(INPUT_GET,"count");
    $keysArr[$beach_image] = $count;
    ?>
    
    <table>
        <tr>
            <th>Beach Image</th>
            <th>Beach</th>
        </tr>
        <tr>
            <td><?php echo $keysArr[0] ;?></td>
            <td>Sunglasses</td>
        </tr>
        <tr>
            <td><?php echo $keysArr[1] ;?></td>
            <td>Sunscreen</td>
        </tr>
        <tr>
            <td><?php echo $keysArr[2] ;?></td>
            <td>Bathing Suit</td>
        </tr>
        <tr>
            <td><?php echo $keysArr[3] ;?></td>
            <td>Hat</td>
        </tr>
    </table>
    <div>
        <?php for($i=1;$i=$count;$i++){?>
            <img src="images/<?= $beach[$beach_image]?>">
        <?php }?>
    </div>