PHP ### A) What Is An Indexed Array?
PHP ### A) What Is An Indexed Array?
- Example: `echo "Hello", " World";` To implement sticky forms, PHP uses the
`$_POST` or `$_GET` superglobal to re-
- **print**: It is also a language construct, but populate form fields with the data from the
it can only output a single string and returns a previous submission.
value (1), which makes it useful in
expressions. Example:
$ages = ["John" => 25, "Jane" => 22, "Doe" => Syntax:
29];
```php
krsort($ages);
setcookie("user", "John", time() + 3600); // expression that evaluates a condition and
Expires in 1 hour returns one value if true and another value if
false.
Here, "user" is the cookie name, "John" is the
value, and `time() + 3600` sets the expiration Syntax:
time to 1 hour.
```php
### f) What is `$_SESSION` in PHP?
(condition) ? value_if_true : value_if_false;
`$_SESSION` is a superglobal array in PHP that
is used to store session variables. Session Example:
variables are stored on the server and can be ```php
used to maintain state across multiple pages
during a user’s visit to a website (i.e., session $age = 20;
persistence).
echo ($age >= 18) ? "Adult" : "Minor"; //
Example: Output: Adult
### j) Explain `mysqli_connect()` in PHP. In PHP, arrays can be categorized into **three
types**:
The `mysqli_connect()` function is used to
open a connection to a MySQL database 1. **Indexed Array**: An array where each
server. It returns a connection object that can element is assigned a numeric index (starting
be used for querying the database. from 0 by default).
- `$port`: (optional) The port number. ### b) What are different arithmetic
operators in PHP?
- `$socket`: (optional) The socket or named
pipe. PHP supports the following **arithmetic
operators**:
Example:
1. **Addition (`+`)**: Adds two numbers.
```php
- Example: `$sum = 5 + 3;`
$connection = mysqli_connect("localhost",
"root", "", "test_db"); 2. **Subtraction (`-`)**: Subtracts one
number from another.
if (!$connection) {
- Example: `$difference = 5 - 3;`
die("Connection failed: " .
mysqli_connect_error()); 3. **Multiplication (`*`)**: Multiplies two
numbers.
}
- Example: `$product = 5 * 3;`
Here are the answers to your PHP-related
questions: 4. **Division (`/`)**: Divides one number by
another.
An **abstract class** in PHP is a class that To implement sticky forms, you can use PHP's
cannot be instantiated directly. It is meant to `$_POST` superglobal to preserve the form
be inherited by other classes, which must data across page reloads.
implement its abstract methods. Abstract
classes can contain both abstract methods Example:
(without implementation) and concrete ```php
methods (with implementation).
<input type="text" name="username"
- **Syntax**: value="<?php echo isset($_POST['username'])
```php ? $_POST['username'] : ''; ?>">
}
Validation can be done **on the client-side**
class Circle extends Shape { (using JavaScript) or **server-side** (using
PHP). Server-side validation is more secure as
public function area() { it ensures data integrity regardless of client
behavior.
return 3.14 * $this->radius * $this-
>radius; // Implement abstract method
} ```php
if (empty($_POST["email"])) {
echo "Email is required"; 2. **PostgreSQL**: Supported through the
`pg_connect()` and `PDO_PGSQL` extensions.
}
3. **SQLite**: Supported via the `SQLite3`
### f) What is the use of `array_slice()` in and `PDO_SQLITE` extensions.
PHP?
4. **Oracle**: Supported through the `oci8`
The **`array_slice()`** function in PHP is used extension.
to extract a portion of an array. It returns a
new array containing a subset of the original 5. **MSSQL (Microsoft SQL Server)**:
array, starting from a specified offset and Supported via the `sqlsrv` extension.
optionally limiting the number of elements.
6. **MariaDB**: Supported using the same
**Syntax**: extensions as MySQL (`mysqli`,
`PDO_MySQL`).
```php
7. **MongoDB**: Supported via the `mongo`
array_slice($array, $offset, $length, or `mongodb` extension.
$preserve_keys);
8. **Other databases**: PHP also supports
- `$array`: The input array. many other databases through PDO (PHP Data
- `$offset`: The starting index. Objects) and specific database extensions.
### j) What is the purpose of the `break` 4. **Database Integration**: PHP has built-in
statement? support for connecting and interacting with
multiple databases such as MySQL,
The `break` statement is used to **exit** PostgreSQL, SQLite, and others.
from a loop (such as `for`, `while`, or
`foreach`) or a `switch` statement. It stops the 5. **Supports Sessions and Cookies**: PHP
loop or switch execution and transfers control allows managing sessions and cookies,
to the next statement following the loop or enabling personalized user experiences and
switch. state management.
for ($i = 0; $i < 10; $i++) { 7. **Flexible and Extensible**: PHP supports
various web frameworks and libraries (like
if ($i == 5) {
Laravel, Symfony) and can be extended with
break; // Exit the loop when $i equals 5 custom functions, classes, and modules.
- The `sumOfDigits()` function loops through
the number by repeatedly extracting the last
8. **Security**: PHP offers various features digit using the modulus operator (`% 10`) and
for improving security, including escaping adding it to the sum.
data for SQL queries, protecting against XSS
and CSRF attacks, and more. - The number is reduced by dividing it by 10
on each iteration (`$num = (int)($num / 10)`).
### b) Write a PHP script to find the sum of
digits of a number. - Finally, it prints the sum of the digits.
You can find the sum of digits of a number by ### c) Explain `for` loop and `foreach` loop
converting the number to a string and then with examples.
iterating through each digit, adding them up.
Here's a PHP script for that: #### 1. **`for` Loop**:
} <?php
$number = 12345; }
**Explanation**:
- The loop starts with `$i = 1`, and continues ?>
until `$i` reaches 5.
```
- In each iteration, the value of `$i` is printed
and incremented by 1. **Output**: `John is 25 years old. Jane is 22
years old. Doe is 29 years old.`
#### 2. **`foreach` Loop**:
$ages = ["John" => 25, "Jane" => 22, "Doe" => - `name`: The name of the cookie.
29];
- `value`: The value stored in the cookie.
foreach ($ages as $name => $age) {
- `expire`: The time when the cookie will
echo "$name is $age years old. "; expire (in Unix timestamp format).
}
- `path`: The path where the cookie is ### e) Explain any two Built-in Array
available (optional). functions in PHP.
- `domain`: The domain that the cookie is PHP provides many built-in functions for
available to (optional). working with arrays. Here are explanations for
two commonly used array functions:
- `secure`: If true, the cookie is only sent over
secure HTTPS connections. #### 1. **`array_merge()`**:
- `httponly`: If true, the cookie can only be The `array_merge()` function merges two or
accessed by the HTTP protocol and not by more arrays into a single array. If the arrays
JavaScript. have string keys, the values from later arrays
will overwrite the values from earlier arrays
**Example**: with the same key. If the arrays have numeric
```php keys, the values are appended.
<?php **Example**:
)
Q2) a) Explain multidimensional array in PHP ```php
with example.
<?php
A **multidimensional array** in PHP is an
array that contains one or more arrays as its // A 3D array representing multiple matrices
elements. It is essentially an array of arrays, $threeDArray = [
allowing you to store data in a table-like
structure. You can create arrays with any [
number of dimensions.
[1, 2],
#### Example of a 2D (two-dimensional)
[3, 4]
array:
],
```php
[
<?php
[5, 6],
// A 2D array representing a matrix (rows and
columns) [7, 8]
$matrix = [ ]
[1, 2, 3], ];
[4, 5, 6], // Accessing an element in the 3D array
(matrix 1, row 0, column 1)
[7, 8, 9]
echo $threeDArray[1][0][1]; // Output: 6
];
?>
// Accessing an element in the 2D array (row
1, column 2) ### b) Write a PHP Program to check
whether the given year is a leap year or not
echo $matrix[1][2]; // Output: 6
(use if-else).
?>
A **leap year** is a year that is divisible by 4,
#### Explanation: but not divisible by 100 unless it is also
divisible by 400. Here's a PHP program to
- `$matrix` is a 2D array where each element check if a given year is a leap year:
is itself an array.
```php
- You can access the elements by specifying
both the row and the column index. <?php
- The first index refers to the row, and the // Function to check if the year is a leap year
second index refers to the column.
function isLeapYear($year) {
#### Example of a 3D (three-dimensional)
if (($year % 4 == 0 && $year % 100 != 0) ||
array:
($year % 400 == 0)) {
return true; const PI = 3.14159; // Defining a constant
in the interface
} else {
public function area(); // Method to
return false; calculate the area
} public function volume(); // Method to
} calculate the volume
// Example usage }
- The `Shape` interface defines the `area()` 5. **`strpos()`**: Finds the position of the first
and `volume()` methods and a constant `PI`. occurrence of a substring in a string.
- The `Cylinder` class implements the `Shape` - Example: `echo strpos("Hello World",
interface and provides concrete "World");` // Output: 6
implementations for the `area()` and 6. **`str_replace()`**: Replaces all
`volume()` methods. occurrences of a substring within a string.
- The `area()` method calculates the surface - Example: `echo str_replace("world", "PHP",
area of the cylinder, and the `volume()` "Hello world!");` // Output: Hello PHP!
method calculates the volume.
7. **`trim()`**: Removes whitespace (or other
- The constant `PI` is accessed using characters) from both ends of a string.
`Shape::PI`.
- Example: `echo trim(" Hello ");` // Output:
### d) What are the built-in functions of Hello
strings in PHP?
8. **`explode()`**: Splits a string into an array
PHP provides a variety of built-in string by a delimiter.
functions that allow manipulation and
processing of string data. Here are some - Example: `print_r(explode(",",
commonly used string functions: "apple,banana,orange"));`
1. **`strlen()`**: Returns the length of a - Output: `Array ( [0] => apple [1] => banana
string. [2] => orange )`
}
Q3) a) Write a PHP script to display the table
// Example array of a number.
)
- The `$number` is set to 5 in this case, but #### 2. **`str_replace()`**:
you can modify it to accept input from the
user if required. The `str_replace()` function replaces all
occurrences of a substring within a string.
- The `for` loop iterates from 1 to 10 and
prints the multiplication result for the given
number. **Example**:
**Output for $number = 5**: ```php
Multiplication table of 5: <?php
5x1=5 $str = "I love programming!";
5 x 2 = 10 $newStr = str_replace("programming", "PHP",
5 x 3 = 15 $str);
?> if ($_SERVER["REQUEST_METHOD"] ==
"POST") {
**Explanation**:
// Get the strings from the user input
- The `strlen()` function calculates and returns
the number of characters in the string `$str`. $string1 = $_POST['string1'];
$string2 = $_POST['string2'];
// Concatenate the strings For example, the factorial of 5 is `5! = 5 × 4 × 3
× 2 × 1 = 120`.
$result = $string1 . " " . $string2;
Here’s a PHP program to calculate the
factorial:
// Display the concatenated result ```php
echo "Concatenated String: " . $result; <?php
} // Function to calculate factorial
?> function factorial($n) {
<!-- HTML form to accept two strings from the if ($n == 0 || $n == 1) {
user -->
return 1; // Factorial of 0 and 1 is 1
<form method="POST">
} else {
String 1: <input type="text" name="string1"
required><br><br> return $n * factorial($n - 1); // Recursive
call
String 2: <input type="text" name="string2"
required><br><br> }
<input type="submit" }
value="Concatenate">
// Example usage
</form>
$number = 5; // Change this number to
#### Explanation: calculate its factorial
- This script first checks if the form has been echo "The factorial of $number is: " .
submitted using the factorial($number);
`$_SERVER["REQUEST_METHOD"] == "POST"`.
?>
- It then collects the two strings (`string1` and
`string2`) from the user input, concatenates #### Explanation:
them with a space in between, and displays - The function `factorial()` calculates the
the result. factorial using recursion. It multiplies the
**Example Output**: number `n` by the factorial of `n - 1` until it
reaches 1.
Concatenated String: Hello World
- The result is printed after the function is
### d) Write a PHP program to calculate the called with the desired number.
factorial of a number.
**Output for $number = 5**:
if ($num % $i == 0) { ```php
if (isPrime($number)) { **Example**:
} echo $y;
} }
```php **Disadvantages**:
- Example: Predicting house prices based on - `hist()` creates a histogram to visualize the
square footage. frequency distribution of the data.
} }
if (empty($_POST["email"])) { ?>
} else {
$email = $_POST["email"];
}
#### b) **Explain Email ID validation in PHP **Example**:
through regular expression.**
<?php **Explanation**:
// Employee records - An array `$employees` contains employee
$employees = array( records, each record is an associative array.
array("empid" => 101, "empname" => "John - A `foreach` loop is used to iterate over the
Doe", "salary" => 50000, "dept" => "HR"), records and display them in an HTML table.
array("empid" => 102, "empname" => "Jane #### e) **Write a PHP program to create
Smith", "salary" => 55000, "dept" => login page and welcome user on next
"Finance"), page.**
array("empid" => 103, "empname" => "Jim Here’s how you can create a simple login page
Brown", "salary" => 48000, "dept" => "IT") with PHP:
exit();
// Welcome the user
} else {
echo "Welcome, " . $_SESSION['username'] .
echo "Invalid credentials!"; "!";
} ?>
} **Explanation**:
exit();
- \( P(Y|X) \) is the probability that the email is fahrenheit <- as.numeric(readline(prompt =
of class \(Y\) (spam or not). "Enter temperature in Fahrenheit: "))
- `plot()` creates a simple scatter plot with cat("Volume of the cuboid is:", volume, "\n")
blue points and lines connecting them. **Explanation**:
#### c) **Write a R program to accept - The volume of a cuboid is calculated using
temperatures in Fahrenheit (F) and print it in the formula: `length * breadth * height`.
Celsius (C).**
```r
```r ```html
} 4. **Checkboxes (`<input
type="checkbox">`)**: Allow users to select
**Explanation**: multiple options.
Here are the answers to the questions you 5. **Select Dropdown (`<select>`)**: Provides
have provided: a dropdown list of options.
```html
```html
```html ```php
**Advantages**:
**Disadvantages**: