JonDecagon Posted March 18, 2017 Share Posted March 18, 2017 I'm trying to create a code that moves a string array A B C D E around based on the amount specified entered into a field in a form and the direction which is also entered into the form. What I want to do is to make the $newarray equal $array when the page is refreshed and the submit button is hit again. That way A B C D E when moved LEFT by 1 will be B C D E A and then if RIGHT and 2 is entered, you will see E A B C D. I've been struggling to get session working and just ended up more lost. Here is the code I got so far. I would greatly appreciate any help with this. <html> <div style="border:1px solid black;font-weight:bold;"> <div style="border:none;">A B C D E</div> <form method="POST"> <input type="text" name="thebutton"/> <input type="text" name="offset"/> <input type="submit" value="SUBMIT"/> </form> </div> <?php session_start(); if (isset($_POST["offset"], $_POST["thebutton"])) { $shift=$_POST["offset"]; $direction=$_POST["thebutton"]; $counter=0; $array=array('A','B','C','D','E'); if ($direction=="LEFT"){ for($i=$shift; $counter+$shift<5; $i++,$counter++){ $newarray[$counter]=$array[$counter+$shift]; } for($j=0; $j<$shift; $j++){ $newarray[$counter + $j]=$array[$j]; } } if ($direction=="RIGHT"){ for($counter=0,$k=5-$shift; $counter<$shift; $counter++){ $newarray[$counter]=$array[$counter+$k]; } for($j=0; $j<5-$shift; $j++){ $newarray[$counter + $j]=$array[$j]; } } echo $newarray[0]; echo $newarray[1]; echo $newarray[2]; echo $newarray[3]; echo $newarray[4]; } ?> </html> Quote Link to comment Share on other sites More sharing options...
requinix Posted March 18, 2017 Share Posted March 18, 2017 1. You can't session_start() if there has been any output. Move that to the very top of the script. 2. If you want to remember the values (and want to use the session for it) then you actually have to put the array into the session. The logic for #2 is simple: if there is an array in $_SESSION already then use that, otherwise use the default ABCDE array. Manipulate that array however you want, then put it back into $_SESSION. Give that a shot. If you have problems, post your new code. Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted March 18, 2017 Share Posted March 18, 2017 Your user interface and the rotation are fairly awkward due to the “LEFT”/“RIGHT” input. I suggest you use positive/negative integers to indicate the direction. You can do this all with a single loop. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.