Hi,
I am trying to create a loop that will create an array from the values posted into a form and then sort them. The user is first asked how many words they want to enter and then a loop creates a form with the appropriate number of text boxes and then an array is created from the values entered and the values are then sorted when the sort button is pressed. However, for some reason it's not creating the array. I have been working at this for 3 days now and I've got to admit defeat, where am I going wrong? (There are some commented out bits form where I was trying to get it working but I've a feeling the problem is the first part of the php, probably the loop)
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Exercise 2 4</title>
</head>
<style type="text/css">
form label {
display: inline-block;
width: 150px;
font-family:Verdana, Geneva, sans-serif;
}
body {font-family:Verdana, Geneva, sans-serif;
}
</style>
<body>
<h1>Sorting Arrays</h1>
<h3>Please enter how words you would like to sort and then click 'sort'</h3>
<form method="post" action="">
<label for="num">Number of words:</label><input type="text" name="num" /><br />
<p><input type="submit" value="Enter" name="enter" /></p>
<p><input type="submit" value="Sort" name="submit" /></p>
</form>
<!-- create table to display results-->
<?php
if(isset($_POST['enter'])){
$num=$_POST['num'];
//while($i <= $num){
for ($i=1;$i<=$num;$i++){
echo "<form>";
echo "<label for=\"words$i\">Word $i</label><input type=\"text\" name=\"words[$i]\" id=\"words$i\" /><br />";
//$words =($_POST['words']);
}
echo "</form>";
}
print_r($words);
echo '<table border="0">';
echo '<tr>';
echo '<td width="150" td align="center"><u>Values</u></td>';
echo '<td width="150" td align="center"><u>Ascending</u></td>';
echo '<td width="150" td align="center"><u>Descending</u></td>';
echo '</tr>';
echo '<tr>';
echo '<td align="center">';
print_r($words);
//when sort is pressed display the values entered
if(isset($_POST['submit'])){
print_r($words);
//$words =$_POST['words'];
foreach ($words as $value){
echo $value.'<br />';
//}
}
echo '</td>';
echo '<td align="center">';
//when sort is pressed display the values entered in ascending orders
if(isset($_POST['submit'])){
//$words =$_POST['words'];
asort($words);
foreach ($words as $value){
echo $value.'<br />';
}
echo '</td>';
echo '<td align="center">';
//when sort is pressed display the values in descending order
if(isset($_POST['submit'])){
//$words =$_POST['words'];
rsort($words);
foreach ($words as $value){
echo $value.'<br />';
}
}
echo '</td>';
echo '</tr>';
echo '</table>';
}
?>
</body>
</html>