Why is my included file executed again when isset(POST['submit'])?

Go To StackoverFlow.com


My included file (include.php) is this:


My main php file is this:


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)

2012-04-04 03:22
by alexx0186
Don't test for the presence of a form field to detect a post. Use $_SERVER['REQUEST_METHOD'] == 'POST' instead - Marc B 2012-04-04 03:34


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.


if (!isset($_SESSION['shuffled'])) {
    $_SESSION['shuffled'] = $myarray;
} else {
    $myarray = $_SESSION['shuffled'];
2012-04-04 03:36
by savinger
Hi, thanks for your response. Never thought of using sessions for this one but I'm going for your solution. Regard - alexx0186 2012-04-04 03:40


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()


2012-04-04 03:31
by Mr Wednesday
Hi, thanks for your response. When you say "POST the array", do you mean declaring something like this: $_POST['array']=$myarray?

Thanks a lo - alexx0186 2012-04-04 03:35

What I meant was that you serialize the array and POST the result as the value of a hidden field in your form. This would allow you to retrieve the desired array after submitting the form - Mr Wednesday 2012-04-04 03:38
Hi Thanks for your response. I am looking into that serialize link. Regard - alexx0186 2012-04-04 03:46