PHP Practical Slip 16 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 = array(
    array("id" => 1, "name" => "John", "course" => "Computer Science"),
    array("id" => 2, "name" => "Mary", "course" => "Information Technology"),
    array("id" => 3, "name" => "David", "course" => "Software Engineering")
);

// Display the Multidimensional Array
echo "<h3>Displaying Multidimensional Array:</h3>";

foreach ($students as $student) {
    echo "ID: " . $student["id"] . "<br>";
    echo "Name: " . $student["name"] . "<br>";
    echo "Course: " . $student["course"] . "<br>";
    echo "----------------------<br>";
}


// Search for a specific element (Example: Search by ID = 2)
$search_id = 2;
$found = false;

echo "<h3>Searching for Student with ID = $search_id</h3>";

foreach ($students as $student) {
    if ($student["id"] == $search_id) {
        echo "Student Found:<br>";
        echo "ID: " . $student["id"] . "<br>";
        echo "Name: " . $student["name"] . "<br>";
        echo "Course: " . $student["course"] . "<br>";
        $found = true;
        break;
    }
}

if (!$found) {
    echo "Student not found.";
}

?>
Spread the love

Leave a Comment

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

Scroll to Top