<?php
include('../includes/header4.php');
// code
error_reporting(E_ALL); // set error reporting to all
//added closing h1 tag
echo('<h1>Lawrence\'s Loops Example-Odd Numbers gathered before Value</h1>');
// Note the variables being passed via the POST Ternary operators.
$step = isset($_POST['step']) ? $_POST['step'] : 0;
//changed values to value
$value = isset($_POST['value']) ? $_POST['value'] : '';
// filter all input taken from the Browser
$step = htmlentities($step);
//values to value
$value = htmlentities($value);
if ($step == 0) // first time into this form
{
?>
<form action="" method="post">
<label for="values">Values</label>
<input type="text" size="36" id="value" name="value" placeholder="(oddnumbers)" value="">
<br><br>
<input type="hidden" name="step" value="1">
<input type="submit" name="submit" value="submit">
</form>
<?php
}
else // else show what form is gathering
{
echo('<p>The following form is gathering');
echo('<pre>');
print_r($_POST); // note this dumps the entire contents of the $_POST array
echo('</pre>');
$y = 0;
$oddnumbers = 0;
$oddnumberslisted = '';
//got rid of counters for simpler odd calculation in single loop
while ($y < $value)
{
if ($y % 2 != 0)
{
$oddnumbers++;
//(add the value of y that did not modulo % to 0 with 2 to $oddnumberslisted, and add a comma with space after each value)
$oddnumberslisted .= $y . ", ";
}
//(parse loop)
$y++;
}
if ($oddnumbers == 1)
{
echo("<h3>There is $oddnumbers Odd Number before its value</h3>");
}
else
{
echo("<h3>There are $oddnumbers Odd Numbers before its value</h3>");
};
//changed length from -3 to -2 (this line gets rid of the last comma in the loop that ends up after the last value)
$oddnumberslisted = substr($oddnumberslisted, 0, -2);
//added spaces around " and " and a space after the comma (this line puts an and before the last value)
$oddnumberslisted = substr_replace($oddnumberslisted, " and ", ((strrpos($oddnumberslisted, ", ", 0)) + 1), 1);
// changed comma to period (this line adds a period at the end of $oddnumberslisted)
$oddnumberslisted .= ".";
echo("Namely: $oddnumberslisted ");
echo('<br>');
// provide a form to try again
?>
<form action="" method="POST">
<input type="hidden" name="step" value="0">
<br>
<input type="submit" name="submit" value="Try Again">
</form>
<?php
}
include('../includes/footer4.php');
?>
Last modified: October 20 2022
Line Count: 96