PHP Practical Slip 7 Q.A

Write a PHP Script for the following:
Declare and Display a multidimensional Array.
Search and display a specific element from a Multidimensional array.

<?php
// Declare a multidimensional array
$students = [
    ["id" => 101, "name" => "Alice", "marks" => 85],
    ["id" => 102, "name" => "Bob", "marks" => 78],
    ["id" => 103, "name" => "Charlie", "marks" => 92],
];

// Display the multidimensional array
echo "<h3>All Students:</h3>";
foreach ($students as $student) {
    echo "ID: " . $student['id'] . ", Name: " . $student['name'] . ", Marks: " . $student['marks'] . "<br>";
}

// Search for a specific element (e.g., student with ID = 102)
$searchId = 102;
$found = false;

foreach ($students as $student) {
    if ($student['id'] == $searchId) {
        echo "<h3>Student Found:</h3>";
        echo "ID: " . $student['id'] . ", Name: " . $student['name'] . ", Marks: " . $student['marks'];
        $found = true;
        break;
    }
}

if (!$found) {
    echo "<h3>Student with ID $searchId not found.</h3>";
}
?>
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top