My included file (include.php) is this:
<?php
$myarray=(a,b,c);
shuffle($myarray);
?>
My main php file is this:
include('include.php');
if isset($_POST['submit_button']){
echo "Button was clicked";
echo $myarray;
}
else {
echo "Not clicked.";
echo $myarray;
}
?>
<form method='POST'><input type='submit' name='submit_button'></form>
Why are the elements of $myarray
displayed in a different order after I clicked the button? Isn't it shuffled only once?
How can I prevent the shuffle from being executed more than one time? (so that I can display the elements of myarray in the same order, before and after the button was clicked)
Your PHP files are interpreted upon every request. As you have it now, there is no memory in your system, so there's no way for your files to "remember" that the array has already been shuffled. Furthermore, if you shuffle the array once, and then load the page a second time, and managed not to shuffle it, the array would be (a,b,c), as the variable is initialized to (a,b,c) and never shuffled.
To do what you want, if I understand it correctly, you could use sessions.
$myarray=(a,b,c);
if (!isset($_SESSION['shuffled'])) {
shuffle($myarray);
$_SESSION['shuffled'] = $myarray;
} else {
$myarray = $_SESSION['shuffled'];
}
This is happening because each time you load the page, the file is being included which also shuffles the array again.
Try using serialize()
and then POST the array in the order you want. Retrieve it using unserialize()
http://www.php.net/manual/en/function.serialize.php
Thanks a lo - alexx0186 2012-04-04 03:35
$_SERVER['REQUEST_METHOD'] == 'POST'
instead - Marc B 2012-04-04 03:34