0% found this document useful (0 votes)
13 views12 pages

Web Programming Practical File 2024-25

The document is a practical file for a Web Programming course at Noida International University, detailing various programming tasks and their solutions in PHP. It includes tasks such as checking if a number is even or odd, displaying the day of the week, swapping numbers, sorting arrays, checking for prime numbers, sending emails, creating a database, printing Fibonacci series, extracting URLs using regex, and demonstrating type juggling. Each task is accompanied by sample code and output results.

Uploaded by

rohitchoud181
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views12 pages

Web Programming Practical File 2024-25

The document is a practical file for a Web Programming course at Noida International University, detailing various programming tasks and their solutions in PHP. It includes tasks such as checking if a number is even or odd, displaying the day of the week, swapping numbers, sorting arrays, checking for prime numbers, sending emails, creating a database, printing Fibonacci series, extracting URLs using regex, and demonstrating type juggling. Each task is accompanied by sample code and output results.

Uploaded by

rohitchoud181
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Noida International University

Department of Computer Science


Practical File – Web Programming
2024-2025

Submitted By: Submitted To:


Rohit kumar Mr. Konark Saxena
BCA-II Sem, Sec-‘D’
NIU-24-19809
Index

Sr Question Page Sign.


No. No
1 Check if a number is even or odd using if-else. 1

2 Display the day of the week based on a number (1-7) using switch. 2

3 Create a program to swap two numbers without a temporary 3


variable.
4 Sort an indexed array in ascending and descending order. 4

5 Write a function to check if a number is prime. 5

6 Write a script to send an email using PHP’s mail() function. 6

7 Create a database students and a table users (id, name, email). 7

8 Print Fibonacci series up to n terms using a for loop. 8

9 Extract all URLs from a given string using regex. 9

10 Create a PHP script that demonstrates type juggling (implicit type 10


conversion).
1. Check if a number is even or odd using if-else.

<?php
$number = 7; // You can change this number

if ($number % 2 == 0) {
echo "$number is even.";
} else {
echo "$number is odd.";
}
?>

Output:- 7 is odd.

1
2. Display the day of the week based on a number (1-7)
using switch.

<?php
$dayNumber = 4; // You can change this value from 1 to 7

switch ($dayNumber) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid number! Please enter a number between 1 and 7.";
}
?>

Output:- Thursday

2
3. Create a program to swap two numbers without a
temporary variable.

<?php
$a = 5;
$b = 10;

echo "Before Swapping:<br>";


echo "a = $a, b = $b<br>";

// Swapping without using a temporary variable


$a = $a + $b; // a becomes 15
$b = $a - $b; // b becomes 5
$a = $a - $b; // a becomes 10

echo "After Swapping:<br>";


echo "a = $a, b = $b";
?>

Output:- Before Swapping:


a = 5, b = 10
After Swapping:
a = 10, b = 5

3
4. Sort an indexed array in ascending and descending
order.

<?php
$numbers = [25, 10, 5, 40, 30];

echo "Original Array:<br>";


print_r($numbers);

// Sort in ascending order


sort($numbers);
echo "<br><br>Array in Ascending Order:<br>";
print_r($numbers);

// Sort in descending order


rsort($numbers);
echo "<br><br>Array in Descending Order:<br>";
print_r($numbers);
?>

Output:- Original Array:


Array ( [0] => 25 [1] => 10 [2] => 5 [3] => 40 [4] => 30 )

Array in Ascending Order:


Array ( [0] => 5 [1] => 10 [2] => 25 [3] => 30 [4] => 40 )

Array in Descending Order:


Array ( [0] => 40 [1] => 30 [2] => 25 [3] => 10 [4] => 5 )

4
5. Write a function to check if a number is prime.

<?php
function isPrime($num) {
if ($num <= 1) return false;
if ($num == 2) return true;

for ($i = 2; $i <= sqrt($num); $i++) {


if ($num % $i == 0) {
return false;
}
}
return true;
}

// Test the function


$number = 13;

if (isPrime($number)) {
echo "$number is a prime number.";
} else {
echo "$number is not a prime number.";
}
?>

Output:- 13 is a prime number.

5
6. Write a script to send an email using PHP’s mail()
function.

<?php
$to = "recipient@[Link]"; // Replace with the recipient's email
address
$subject = "Test Email from PHP";
$message = "Hello! This is a test email sent using PHP's mail()
function.";
$headers = "From: sender@[Link]"; // Replace with your sender
email

if (mail($to, $subject, $message, $headers)) {


echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>

Output:- Email sent successfully!

6
7. Create a database students and a table users (id, name,
email).
<?php
$servername = "localhost";
$username = "root"; // default username for XAMPP/WAMP
$password = ""; // default password is empty for XAMPP
$dbname = "students";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
if ($conn->query($sql) === TRUE) {
echo "Database 'students' created successfully.<br>";
} else {
echo "Error creating database: " . $conn->error;
}

// Select the database


$conn->select_db($dbname);

// Create table
$tableSql = "CREATE TABLE IF NOT EXISTS users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE
)";

if ($conn->query($tableSql) === TRUE) {


echo "Table 'users' created successfully.";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>
Output:- Database 'students' created successfully.
Table 'users' created successfully.

7
8. Print Fibonacci series up to n terms using a for loop.

<?php
$n = 10; // Number of terms in the Fibonacci series

$first = 0;
$second = 1;

echo "Fibonacci series up to $n terms:<br>";

for ($i = 0; $i < $n; $i++) {


echo $first . " ";

// Generate next term


$next = $first + $second;
$first = $second;
$second = $next;
}
?>

Output:- Fibonacci series up to 10 terms:


0 1 1 2 3 5 8 13 21 34

8
9. Extract all URLs from a given string using regex.

<?php
$string = "Here are some links: [Link]
[Link] and [Link]

$pattern = "/\bhttps?:\/\/\S+/i"; // Regex to match http or https URLs

preg_match_all($pattern, $string, $matches);

echo "Extracted URLs:<br>";


foreach ($matches[0] as $url) {
echo $url . "<br>";
}
?>

Output:- Extracted URLs:


[Link]
[Link]

9
10. Create a PHP script that demonstrates type juggling
(implicit type conversion).

<?php
$number = 10; // Integer
$text = "5"; // String

// Implicit type conversion happens here


$result = $number + $text; // PHP converts the string '5' to an integer
and adds it to $number

echo "The result of adding number and text is: $result<br>"; // Output:
15

$floatValue = 3.5; // Float


$sum = $number + $floatValue; // PHP implicitly converts $number to
float

echo "The result of adding integer and float is: $sum<br>"; // Output:
13.5

$booleanValue = true; // Boolean


$sum2 = $number + $booleanValue; // PHP converts 'true' to 1 and adds
it to $number

echo "The result of adding integer and boolean is: $sum2<br>"; //


Output: 11
?>

Output:- The result of adding number and text is: 15


The result of adding integer and float is: 13.5
The result of adding integer and boolean is: 11

10

Common questions

Powered by AI

A function to determine if a number is prime checks divisibility from 2 up to the square root of the number. Begin by ensuring the number is greater than 1. If the number is 2, it is prime. For numbers greater than 2, loop from 2 to sqrt(num), checking if divisible by any number. If true, the number isn't prime; otherwise, it is. Example: `function isPrime($num) { if ($num <= 1) return false; for ($i=2; $i <= sqrt($num); $i++) { if ($num % $i == 0) return false; } return true; }` .

To extract URLs from a string using regex in PHP, utilize `preg_match_all()` with a pattern that matches typical URL formats. Example: `$pattern = "/\bhttps?:\/\/\S+/i"; preg_match_all($pattern, $string, $matches);`. The regex focuses on protocols (http, https) followed by any non-space sequence, effectively capturing URLs from text .

To sort an array in PHP, utilize the built-in functions `sort()` for ascending order and `rsort()` for descending order. Initially, call `sort($numbers)` to sort the array elements in ascending order. Then, use `rsort($numbers)` to re-sort the elements in descending order .

To determine if a number is even or odd in PHP using an 'if-else' statement, you can check the remainder when dividing the number by 2. If the remainder is 0, the number is even; otherwise, it is odd. Example code: `if ($number % 2 == 0) { echo "$number is even."; } else { echo "$number is odd."; }` .

Using PHP's mail() function requires specifying the recipient's address, subject, message, and headers (optional, for additional fields like 'From'). To send an email: `$to = "recipient@example.com"; $subject = "Test Email"; $message = "Hello!"; $headers = "From: sender@example.com"; if(mail($to, $subject, $message, $headers)) { echo "Email sent successfully!"; }` .

Creating a database and table in MySQL via PHP involves establishing a connection using `mysqli` constructors, then executing SQL queries to create the database and table. Begin by connecting to the server: `$conn = new mysqli($servername, $username, $password);`. Create the database: `$sql = "CREATE DATABASE students";`. Select the database and create a table: `$conn->select_db($dbname); $tableSql = "CREATE TABLE users (id INT, name VARCHAR(50), email VARCHAR(100))";`. Execute these queries with `query()` method checks .

A switch statement can map a number to a weekday by matching the number to case labels. For instance, a number between 1-7 can be associated with a weekday, like '1' for Monday and '2' for Tuesday. If no matching case exists, the default case executes, displaying an error message. Example implementation: `switch ($dayNumber) { case 1: echo "Monday"; break; ...default: echo "Invalid number! Please enter a number between 1 and 7."; }` .

To print the Fibonacci series up to 'n' terms using a for loop in PHP, initialize the first two terms, set a loop to iterate 'n' times, print each term, calculate the next term by summing the previous two, and update them: `$first = 0; $second = 1; for ($i = 0; $i < $n; $i++) { echo $first . " "; $next = $first + $second; $first = $second; $second = $next; }` .

Swapping two numbers without a temporary variable in PHP can be performed using arithmetic operations. For example: `$a = $a + $b; $b = $a - $b; $a = $a - $b;`. This method uses addition and subtraction to reassign values between two variables, effectively swapping them .

Type juggling in PHP refers to implicit type conversion during operations. PHP automatically converts a variable type to another type based on context. For example, adding a string to an integer (`$result = 10 + "5";`) converts the string to an integer, yielding 15. Similarly, PHP converts an integer to a float (`$sum = 10 + 3.5;`) or a boolean to an integer during arithmetic operations, enabling seamless calculations: integer + boolean (`$sum = 10 + true;` results in 11).

You might also like