I took on a PHP challenge to have a multiplication table that accepted and input and multiplied that input 1 - 10 times.
This allowed me to practice the following concepts beyond Laravel:
Forms
While loops
Error handling
Simple form handling
Here is the code I used:
I refactored the code as the table's heading row eventually created could also be a while loop.
The main new concept here is while loops so here is a breakdown of what is going on in a while loop.
$x = 0;
I start by setting the value of the variable ($x) to an integer value of 0 so there is a condition to check against.
while($x < 10){ //code }
While statements start with the condition that must be met. So as long as the value as $x is less that 10 the code between the { } will run. As long as the condition is true the code will run. It will stop running when the code is no longer true.
This is useful if you only want something to run a set number of times like in my multiplication.
Eventually, there is a point where you want the loop to stop.
while($x < 10){ //code $x++;}
I can keep iterating my number by one on every loop with the $x++ which is an operator that will increment the value of $x in every loop.
So after 10 loops $x will contain the value of 11 and therefore will never run as it will no longer meet the initial condition.
My multiplication table in action
<?php
//retrives the post data and saves it as a vairable value using a get request.
if($_GET['userNumber']){
$userNumber = $_GET['userNumber'];
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Multiplication</title>
</head>
<body>
<table>
<tr>
//checks a $userNumber exists, essentially checks the form was submitted
<?php if(isset($userNumber)) {
// the first while loop condition is set
$z = 1;
// while condition is true in a new table cell echo out the $userNumber and the itteration number which in this case is valuble to the ux, then increment the value of $z by 1.
while($z < 11){
echo "<td>$userNumber x $z</td>";
$z++;
}
//close row start another row
echo "</tr><tr>";
// set the next condition
$x = 1;
// while condition is true in a new table cell multiply the increment value by the user inputed value then echo out the result, then again increment the origional conditional value.
while($x < 11){
$y = $x * $userNumber;
echo "<td>$y</td>";
$x++;
}
//close the table
echo "</tr></table>";
}
?>
<h1>Multiplication table</h1>
<p>Enter the number you would like to generate a table here.</p>
<!-- a post action which posts to the header and action is blank so it posts to the same page -->
<form type="post" action="">
<p><label for="userNumber">Your number:</label></p>
<input type="text" name="userNumber" value="<?=$_GET['userNumber'] ?? '';?>" >
<button type="submit">Submit</button>
</form>
</body>
</html>
As a side note.
I could have used a for loop instead.
This approach may be more concise and easier to read.
Ultimately, both the original code with while loops and the refactored code with for loops achieve the same result.
//How I might have used a for loop
for ($z = 1; $z <= 10; $z++) {
echo "<td>$userNumber x $z</td>";
}
A for loop requests 3 parameters$z = 1
The comparison condition is set,$z <= 10
The condition is set$z++
The increment rule is set
Otherwise, it works just like a while loop except for the fact the increment no longer needs to be declared as it's already handled.
I'm liking for loops the more I look at them.
Additional challenges
Array
You have an array of integers. Your task is to write a PHP function called findMinMax
that finds the smallest and largest integers in the array. The function should take the array as an argument and return an array with two elements: the smallest and largest integers.
Write the findMinMax
function with the following signature:
phpCopy codefunction findMinMax($arr) {
// Your code here
}
For example, if the input array is:
phpCopy code$arr = [4, 2, 9, 5, 1, 7];
The function should return:
phpCopy code[1, 9]
Here's a PHP function to find the smallest and largest integers in an array:
phpCopy codefunction findMinMax($arr) {
if (empty($arr)) {
return []; // Handle an empty array case
}
$min = $max = $arr[0]; // Initialise min and max with the first element
foreach ($arr as $value) {
if ($value < $min) {
$min = $value; // Update min if we find a smaller value
} elseif ($value > $max) {
$max = $value; // Update max if we find a larger value
}
}
return [$min, $max];
}
// Test the function with an example array
$arr = [4, 2, 9, 5, 1, 7];
$result = findMinMax($arr);
print_r($result); // Output: Array([0] => 1 [1] => 9)
This function initializes the minimum and maximum values with the first element of the array, and then it iterates through the array to find the actual minimum and maximum values. Finally, it returns them in a new array.
Working with switch statements and turnery operators
The task is to create a PHP function called gradeToLetter
that takes an integer grade as input and returns the corresponding letter grade using a switch statement. If the grade is below 60, it should return 'F'. Otherwise, use the following grading scale:
90-100: 'A'
80-89: 'B'
70-79: 'C'
60-69: 'D'
Additionally, implement the function to include a ternary operator to determine if the grade is 'Pass' or 'Fail'. If the grade is 60 or above, it should return 'Pass'; otherwise, it should return 'Fail'.
Write the gradeToLetter
function with the following signature:
phpCopy codefunction gradeToLetter($grade) {
// Your code here
}
For example, if the input grade is 75, the function should return:
phpCopy code['letter' => 'C', 'pass' => 'Pass']
If the input grade is 45, the function should return:
phpCopy code['letter' => 'F', 'pass' => 'Fail']
Answer:
Here's a PHP function that uses a switch statement and a ternary operator to convert a numeric grade into a letter grade and pass/fail status:
phpCopy codefunction gradeToLetter($grade) {
$letter = 'F'; // Default to 'F'
$pass = 'Fail'; // Default to 'Fail'
switch (true) {
case ($grade >= 90 && $grade <= 100):
$letter = 'A';
$pass = 'Pass';
break;
case ($grade >= 80 && $grade < 90):
$letter = 'B';
$pass = 'Pass';
break;
case ($grade >= 70 && $grade < 80):
$letter = 'C';
$pass = 'Pass';
break;
case ($grade >= 60 && $grade < 70):
$letter = 'D';
$pass = 'Pass';
break;
}
return ['letter' => $letter, 'pass' => ($pass === 'Pass') ? 'Pass' : 'Fail'];
}
// Test the function with example grades
$grade1 = 75;
$result1 = gradeToLetter($grade1);
print_r($result1); // Output: Array([letter] => C [pass] => Pass)
$grade2 = 45;
$result2 = gradeToLetter($grade2);
print_r($result2); // Output: Array([letter] => F [pass] => Fail)
This function uses a switch statement to determine the letter grade and a ternary operator to decide if it's a 'Pass' or 'Fail'.