Semester
Subject
Year
Tribhuwan University
2078
Bachelor Level / Third Year / Fifth Semester / Science
(Web Technology)
Full Marks: 60
Pass Marks: 24
Time: 3 Hours
Candidates are required to give their answers in their own words as for as practicable.
The figures in the margin indicate full marks.
Long Answers Questions
Array in PHP is a special variable that can hold multiple values of same or different data types under a single name, accessed using index or key.
An array is a data structure that stores one or more similar or dissimilar type of values in a single variable. In PHP, arrays can be defined in two ways:
array() function: $arr = array("value1", "value2", "value3");$arr = ["value1", "value2", "value3"];Types of Arrays in PHP:
A multidimensional array is an array of arrays. Here, each element of the main array is itself an associative array containing pcode, pname, and price.
<?php
// Defining a multidimensional array named Product
$Product = array(
array("pcode" => "P001", "pname" => "Laptop", "price" => 45000),
array("pcode" => "P002", "pname" => "Mouse", "price" => 500),
array("pcode" => "P003", "pname" => "Keyboard", "price" => 1200)
);
?>
<!DOCTYPE html>
<html>
<head>
<title>Product Table</title>
</head>
<body>
<h2>Product Details</h2>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Price (Rs.)</th>
</tr>
<?php
// Defining multidimensional array
$Product = array(
array("pcode" => "P001", "pname" => "Laptop", "price" => 45000),
array("pcode" => "P002", "pname" => "Mouse", "price" => 500),
array("pcode" => "P003", "pname" => "Keyboard", "price" => 1200)
);
// Displaying array values in table rows using loop
for($i = 0; $i < count($Product); $i++)
{
echo "<tr>";
echo "<td>" . $Product[$i]["pcode"] . "</td>";
echo "<td>" . $Product[$i]["pname"] . "</td>";
echo "<td>" . $Product[$i]["price"] . "</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
| Product Code | Product Name | Price (Rs.) |
|---|---|---|
| P001 | Laptop | 45000 |
| P002 | Mouse | 500 |
| P003 | Keyboard | 1200 |
count($Product) returns the number of elements (3 in this case)$Product[$i]$Product[$i]["pcode"]for loop iterates through all instances and generates table rows dynamicallyConclusion: Arrays in PHP are powerful data structures. Multidimensional arrays allow us to store complex data like product catalogs, and when combined with HTML, we can display this data in a well-formatted table on a webpage.
Short Answers Questions