Skip to main content

Practical-08

Write a PHP program to prepare student Mark sheet using Switch statement.

Introduction

Writing programs in a programming language is one of the most important tasks of a computer science student. However, starting off as a beginner in coding can be a daunting task. In this article, we will discuss how to write a PHP program to prepare a student mark sheet using the switch statement. Switch statements are one of the most effective ways to give output based on different conditions. This is especially useful when preparing a mark sheet, as you need to choose the grade of a student based on the marks obtained.

PHP is a popular scripting language that is widely used in web development. We will be using PHP to write our program, as it is one of the most user-friendly scripting languages for beginners. We will also be writing code for HTML for the view part.

This program will provide us with a user-friendly interface and illustrate how the switch statement can be used effectively to display student marks. It will also help students understand basic concepts of web development using PHP. So let's get started and learn how to prepare a student mark sheet using the switch statement in PHP.

Code

// Create Array
$students = [
["name" => "Alice", "mark" => 90],
["name" => "Bob", "mark" => 80],
["name" => "Carol", "mark" => 70],
["name" => "Dan", "mark" => 60],
["name" => "Eric", "mark" => 50],
["name" => "Frank", "mark" => 40],
["name" => "George", "mark" => 30],
["name" => "Harry", "mark" => 20]
];

// Start HTML
echo "<table>";
echo "<tr><th>Name</th><th>Mark</th><th>Grade</th></tr>";

// Create table
foreach($students as $s) {
echo "<tr><td>".$s["name"]."</td><td>".$s["mark"]."</td><td>";

//Grade switch statement
switch(true) {
case ($s["mark"] >= 90): $output = "A"; break;
case ($s["mark"] >= 80): $output = "B"; break;
case ($s["mark"] >= 70): $output = "C"; break;
case ($s["mark"] >= 60): $output = "D"; break;
case ($s["mark"] >= 50): $output = "E"; break;
default: $output = "F"; break;
}
echo $output;

// End HTML
echo "</td></tr>";
}
echo "</table>";

Output

Name   Mark   Grade
Alice 90 A
Bob 80 B
Carol 70 C
Dan 60 D
Eric 50 E
Frank 40 F
George 30 F
Harry 20 F
Explanation

In this code, we first create an array of students with their names and their marks. We then start the HTML code part, create the necessary labels and create a table to display the data. Then, we use a foreach loop to loop through the students and create a row for each. Inside the loop, we use a switch statement to check the mark of each student and assign the corresponding grade to them. Finally, we echo out the grade that has been assigned to the student.

Get Help