I'm new to php, I'm trying to create a program that asks the user for number of elements, then input these elements, then bubbles sort them.
<?php
function bubbleSort(array $arr)
{
$n = sizeof($arr);
for ($i = 1; $i < $n; $i++) {
$flag = false;
for ($j = $n - 1; $j >= $i; $j--) {
if($arr[$j-1] > $arr[$j]) {
$tmp = $arr[$j - 1];
$arr[$j - 1] = $arr[$j];
$arr[$j] = $tmp;
$flag = true;
}
}
if (!$flag) {
break;
}
}
return $arr;
}
// Example:
$arr = array(255,1,'a',3,45,5);
$result = bubbleSort($arr);
print_r($result);
?>
My code works fine if I store the array, What I'm trying to do is to ask the user for the input instead of storing it in the code. Can anyone help me out of how to ask the user of how many elements needed and then input these elements?
Try this html code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Submit a Ticket</title>
<style type="text/css" media="screen">
.hidden {
display: none;
}
</style>
</head>
<body>
<form name="form1" id="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>">
<h5>Bubble Sort</h5>
<h6>Fill the values</h6>
<label>Value 1<input type="text" name="bubble_values[]" id="bubble_values1" size="10" maxlength="10"></label><br>
<label>Value 2<input type="text" name="bubble_values[]" id="bubble_values2" size="10" maxlength="10"></label><br>
<label>Value 3<input type="text" name="bubble_values[]" id="bubble_values3" size="10" maxlength="10"></label><br>
<label>Value 4<input type="text" name="bubble_values[]" id="bubble_values4" size="10" maxlength="10"></label><br>
<label>Value 5<input type="text" name="bubble_values[]" id="bubble_values5" size="10" maxlength="10"></label><br>
<input type="submit" value="Sort it!" id="bt-submit">
</form>
<h3>Result</h3>
<?php
function bubbleSort(array $arr)
{
$n = sizeof($arr);
for ($i = 1; $i < $n; $i++) {
$flag = false;
for ($j = $n - 1; $j >= $i; $j--) {
if($arr[$j-1] > $arr[$j]) {
$tmp = $arr[$j - 1];
$arr[$j - 1] = $arr[$j];
$arr[$j] = $tmp;
$flag = true;
}
}
if (!$flag) {
break;
}
}
return $arr;
}
// Example:
if (isset($_POST['bubble_values']) && !empty($_POST['bubble_values'])) {
echo '<pre>';
echo 'Before sort: ';
print_r($_POST['bubble_values']);
echo '<br>--------------------<br>';
echo 'After sort:' ;
print_r(bubbleSort($_POST['bubble_values']));
echo '</pre>';
}
?>
</body>
</html>