Question

Each time I click the next button it's stuck up in the 1st element that has been search in the array. Here's my sample code:

<?php

$letter = 'A';

if (isset($_POST["next"])) 
{
    if(isset($next))
    {
        unset($letter);
        $letter = $next;
    }

    $alphabet = array('A', 'B', 'C', 'D', 'E');

    $get = array_search($letter, $alphabet);

    $next = $alphabet[$get + 1];

    echo $next;
}

?>

<form name="alphabet" method="post"> 
<input type="submit"  name="next" value="next"/>
</form>

The output is:

B

My desired output is:

A-> B-> C-> D

how to go to every next element everytime I click the next button & if the last element shown I want it to go to the 1st element in the array like it was loop to the 1st element. I don't want to use a $_GET I want a $_POST. Kindly help me out this one? Thank you.

Was it helpful?

Solution

Try this. You need to post the variable back to the script so that upon each page load, it can know what the previous value was.

<?php
        $letter = 'A';

        if (isset($_POST["letter"]))
        {
            $letter = $_POST["letter"];

            $alphabet = array('A', 'B', 'C', 'D', 'E');

            $get = array_search($letter, $alphabet);

            if($get < (count($alphabet) - 1))
            {
                $get++;
            }
            else
            {
                $get = 0;
            }

            $letter = $alphabet[$get];

            echo $letter;
        }

        ?>

        <form name="alphabet" method="post">
            <input type="hidden"  name="letter" value="<?php echo $letter ?>" />
            <input type="submit"  value="next" />
        </form>

Edit: Have added a check on the index variable $get to only increment if it is not at the end of the array, otherwise it should reset.

OTHER TIPS

Try this. We are passing the current letter as a hidden post variable.

<?php

$alphabet = array('A', 'B', 'C', 'D', 'E');
$next = 'A';   //for the first call of page.
if (isset($_POST["next"])) 
{

    $letter = $_POST['letter'];

    $get = array_search($letter, $alphabet);

    $next = $alphabet[($get + 1)%count($alphabet)];  //for loop over array

}

echo $next;
?>

<form name="alphabet" method="post"> 
<input type="hidden"  name="letter" value="<?php echo $next;?>"/>
<input type="submit"  name="next" value="next"/>
</form>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top