0% found this document useful (0 votes)
6 views

Php Lab Manual

The document contains a series of PHP programming tasks and examples, including calculating compound interest, areas of geometric shapes, string concatenation, number checks, quadratic equation roots, square root calculation, Floyd's triangle generation, mean and standard deviation calculations, histogram creation, date formatting, and Fibonacci series generation. Each task is accompanied by code snippets demonstrating the implementation of the required functionality. The document serves as a PHP lab manual for students in the Department of AIML at GMIT.

Uploaded by

islamicbooks673
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Php Lab Manual

The document contains a series of PHP programming tasks and examples, including calculating compound interest, areas of geometric shapes, string concatenation, number checks, quadratic equation roots, square root calculation, Floyd's triangle generation, mean and standard deviation calculations, histogram creation, date formatting, and Fibonacci series generation. Each task is accompanied by code snippets demonstrating the implementation of the required functionality. The document serves as a PHP lab manual for students in the Department of AIML at GMIT.

Uploaded by

islamicbooks673
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1a Develop a PHP program to calculate Compound Interest.

1b. Develop a PHP program to calculate Compound Interest.

1a. Develop a PHP program to calculate areas of Triangle and


Rectangle.

<?php
// Function to calculate the area of a triangle
function calculateTriangleArea($base, $height)
{
return 0.5 * $base * $height;
}

// Function to calculate the area of a rectangle


function calculateRectangleArea($length, $width)
{
return $length * $width;
}

// Get user input for triangle dimensions


echo "Enter the base of the triangle: ";
$base =fgets(STDIN);

echo "Enter the height of the triangle: ";


$height =fgets(STDIN);

// Calculate and display the area of the triangle


$triangleArea = calculateTriangleArea($base, $height);
Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 1
echo "The area of the triangle is: " . $triangleArea . "\n";

// Get user input for rectangle dimensions


echo "Enter the length of the rectangle: ";
$length =fgets(STDIN);

echo "Enter the width of the rectangle: ";


$width =fgets(STDIN);

// Calculate and display the area of the rectangle


$rectangleArea = calculateRectangleArea($length, $width);
echo "The area of the rectangle is: " . $rectangleArea . "\n";
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 2


1b.Develop a PHP program to calculate Compound Interest.

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 3


2.Demonstrating the various forms to concatenate multiple strings Develop
program(s) to demonstrate concatenation of strings:

(i) Strings represented with literals (single quote or double quote)


(ii) Strings as variables
(iii) Multiple strings represented with literals (single quote or double
quote) and variables
(iv) Strings and string variables containing single quotes as part string
contents
(v) Strings containing HTML segments having elements with attributes

//(i)Strings represented with literals (single quote or double quote)

<?php
// Using single quotes
$string1 = 'Hello';
$string2 = 'World';
$concatenatedString1 = $string1 . ' ' . $string2;

echo $concatenatedString1; // Output: Hello World

// Using double quotes


$concatenatedString2 = "$string1 $string2";
echo $concatenatedString2; // Output: Hello World
?>

//(ii)Strings as variables

<?php
// Defining string variables
$firstName = 'John';
$lastName = 'Doe';

// Concatenating string variables


$fullName = $firstName . ' ' . $lastName;
echo $fullName; // Output: John Doe
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 4


//iii)Multiple strings represented with literals (single quote or double
quote) and variables

<?php
$greeting = 'Hello';
$name = 'Alice';
$punctuation = '!';

// Concatenating multiple literals and variables


$message = $greeting . ', ' . $name . $punctuation;

echo $message; // Output: Hello, Alice!


?>

(vi) Strings and string variables containing single quotes as part string
contents

<?php
$quote = "It's a beautiful day!";
$author = 'John';

// Concatenating strings with single quotes


$fullQuote = $quote . " - " . $author;

echo $fullQuote; // Output: It's a beautiful day! - John


?>

// v)Strings containing HTML segments having elements with


attributes
<?php
$title = 'Welcome to My Website';
$content = 'This is a simple PHP string concatenation example.';

// Concatenating HTML segments


$htmlOutput = "<h1>$title</h1>" .
"<p>$content</p>" .

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 5


"<a href='https://example.com' target='_blank'>Click
here</a>";
echo $htmlOutput;
// Output:
// <h1>Welcome to My Website</h1>
// <p>This is a simple PHP string concatenation example.</p>
// <a href='https://example.com' target='_blank'>Click here</a>
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 6


3a.Develop a PHP Program(s) to check given number is:

(i) Odd or even


(ii) Divisible by a given number (N)
(iii) Square of a another number

<?php
function checkNumber($number)
{
// Check if the number is odd or even
if ($number % 2 == 0)
{
$oddEven = "even";
}
else
{
$oddEven = "odd";
}

// Check if the number is divisible by a given number (N)


$divisibleBy = 5;
if ($number % $divisibleBy == 0)
{
$divisible = "Yes, $number is divisible by $divisibleBy.";
}
else
{
$divisible = "No, $number is not divisible by $divisibleBy.";
}
// Check if the number is the square of another number
$square = sqrt($number);
if ($square * $square == $number)
{
$isSquare = "Yes, $number is the square of $square.";
}
else
{
$isSquare = "No, $number is not the square of any integer.";
}
// Display the results
echo "Number: $number\n";
echo "The number is $oddEven.\n";
echo "$divisible\n";
echo "$isSquare\n";

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 7


}
// Example usage
$number = 25;
checkNumber($number);
?>

Output:

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 8


3b.Develop a PHP Program to compute the roots of a quadratic equation by
accepting the coefficients. Print the appropriate messages .

<?php
// Function to calculate the roots of a quadratic equation

function calculateRoots($a, $b, $c)


{
// Calculate the discriminant
$discriminant = ($b * $b) - (4 * $a * $c);

// Check the nature of the roots based on the discriminant


if ($discriminant > 0)
{
// Two distinct real roots
$root1 = (-$b + sqrt($discriminant)) / (2 * $a);
$root2 = (-$b - sqrt($discriminant)) / (2 * $a);
echo "The roots are real and distinct:\n";
echo "Root 1: " . round($root1, 2) . "\n";
echo "Root 2: " . round($root2, 2) . "\n";
} elseif ($discriminant == 0)
{
// One double real root
$root = -$b / (2 * $a);
echo "The roots are real and the same (double root):\n";
echo "Root: " . round($root, 2) . "\n";
} else
{
// Complex roots
$realPart = -$b / (2 * $a);
$imaginaryPart = sqrt(-$discriminant) / (2 * $a);
echo "The roots are complex and distinct:\n";
echo "Root 1: " . round($realPart, 2) . " + " . round($imaginaryPart, 2) . "i\n";
echo "Root 2: " . round($realPart, 2) . " - " . round($imaginaryPart, 2) . "i\n";
}
}

// Accepting coefficients from the user


echo "Enter the coefficients of the quadratic equation (ax^2 + bx + c = 0):\n";
echo "Coefficient a: ";
$a = fgets(STDIN);
echo "Coefficient b: ";
$b = fgets(STDIN);
echo "Coefficient c: ";
$c = fgets(STDIN);
Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 9
// Validate that 'a' is not zero
if ($a == 0) {
echo "Coefficient 'a' cannot be zero for a quadratic equation.\n";
} else {
// Calculate and display the roots
calculateRoots($a, $b, $c);
}
?>

case 1:
If you input
a=1,
b=−3,
c=2

The roots are real and distinct:


Root 1: 2.00
Root 2: 1.00

case 2:
If you input

a=1,
b=2,
c=1:

The roots are real and the same (double root):


Root: -1.00

case 3:
If you input
a=1,
b=1,
c=1:

The roots are complex and distinct:


Root 1: -0.50 + 0.87i
Root 2: -0.50 - 0.87i

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 10


4a.Develop a PHP program to find the square root of a number by using the
newton’s algorithm

<?php
function sqrtt($num, $precision = 0.0001)
{
$x = $num;
$y = 1;
while ($x - $y > $precision)
{
$x = ($x + $y) / 2;
$y = $num / $x;
}
return round ($x, 4);
}

// Example usage
$number = 101;
$result = sqrtt($number);
echo "The square root of $number is: $result";
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 11


4b.Develop a PHP program to generate Floyd’s triangle.

<?php

function generateFloydsTriangle($rows)
{
$number = 1; // Starting number
for ($i = 1; $i <= $rows; $i++)
{
// Print each row
for ($j = 1; $j <= $i; $j++)
{
echo $number . " ";
$number++; // Increment the number for the next position
}
echo "\n"; // New line after each row
}
}

// Set the number of rows for Floyd's Triangle


$numberOfRows = 5; // You can change this number to generate more or fewer
rows
generateFloydsTriangle($numberOfRows);

?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 12


5a. Develop a PHP application that reads a list of numbers and calculates
mean and standard deviation.

<?php

/**
* Function to calculate the mean of an array
*
* @param array $numbers
* @return float
*/
function calculateMean(array $numbers): float {
$count = count($numbers);
if ($count === 0) {
return 0; // Avoid division by zero
}
$sum = array_sum($numbers);
return $sum / $count;
}

/**
* Function to calculate the standard deviation of an array
*
* @param array $numbers
* @return float
*/
function calculateStandardDeviation(array $numbers): float
{
$mean = calculateMean($numbers);
$sumOfSquares = 0;

foreach ($numbers as $number)


{
$sumOfSquares += pow($number - $mean, 2);
}

$count = count($numbers);
if ($count <= 1)
{
return 0; // Standard deviation is not defined for 0 or 1 element
}

return sqrt($sumOfSquares / ($count - 1)); // Sample standard deviation


}

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 13


// Example dataset
$data = [10, 12, 23, 23, 16, 23, 21, 16];

// Calculate mean and standard deviation


$mean = calculateMean($data);
$standardDeviation = calculateStandardDeviation($data);

// Output the results


echo "Data: " . implode(", ", $data) . PHP_EOL;
echo "Mean: " . number_format($mean, 2) . PHP_EOL;
echo "Standard Deviation: " . number_format($standardDeviation, 2) . PHP_EOL;

?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 14


5b.Develop a PHP application that reads scores between 0 and 100
(possibly including both 0 and 100) and creates a histogram array whose
elements contain the number of scores between 0 and 9, 10 and 19, etc.
The last “box” in the histogram should include scores between 90 and
100. Use a function to generate the histogram.
<?php
function createHistogram($scores) {
$histogram = array_fill(0, 11, 0);

foreach ($scores as $score) {


$index = floor($score / 10);
$histogram[$index]++;
}

return $histogram;
}

// Example usage
$scores = [85, 92, 77, 68, 92, 88, 75, 82, 91, 70, 65, 88, 95, 72, 78, 90, 85, 80, 75,
88];

$histogram = createHistogram($scores);

echo "Histogram:\n";
for ($i = 0; $i < 10; $i++) {
echo sprintf("%2d-%2d: %d\n", $i * 10, $i * 10 + 9, $histogram[$i]);
}
echo "90-100: " . $histogram[10] . "\n";

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 15


6a.Develop PHP program to demonstrate the date() with different
parameter options.

<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");


echo " ".$today;
$today = date("m.d.y");
echo "\n ".$today;
$today = date("j, n, Y"); // 10, 3, 2001
echo "\n ".$today;
$today = date("Ymd"); // 20010310
echo "\n ".$today;
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6
Satpm01
echo "\n ".$today;
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
echo "\n".$today;
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
echo "\n".$today;
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
echo "\n".$today;
$today = date("H:i:s"); // 17:16:18
echo "\n".$today;
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL
DATETIME format)
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 16


6b.Develop a PHP program to generate the Fibonacci series using a
recursive function.

<?php
// Function to calculate Fibonacci number using recursion
function fibonacci($n) {
// Base cases
if ($n <= 0) {
return 0; // Fibonacci of 0 is 0
} elseif ($n == 1) {
return 1; // Fibonacci of 1 is 1
} else {
// Recursive case
return fibonacci($n - 1) + fibonacci($n - 2);
}
}

// Function to print the Fibonacci series up to the nth term


function printFibonacciSeries($terms)
{
echo "Fibonacci Series up to $terms terms:\n";
for ($i = 0; $i < $terms; $i++)
{
echo fibonacci($i) . " ";
}
echo "\n";
}

// Example usage
$numberOfTerms = 10; // Change this value to generate more or fewer terms
printFibonacciSeries($numberOfTerms);
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 17


7. Develop a PHP program to accept the file and perform the following
(i) Print the first N lines of a file
(ii) Update/Add the content of a file

<?php
// Function to print the first N lines of a file

function printFirstNLines($filename, $N)


{
$lines = file($filename, FILE_IGNORE_NEW_LINES);
for ($i = 0; $i < min(count($lines), $N); $i++)
{
echo $lines[$i] . "\n";
}
}

// Function to update/add content to a file


function updateFileContent($filename, $content)
{
file_put_contents($filename, $content, FILE_APPEND);
}

// Example usage
$filename = "ple.txt";
$N = 5; // Number of lines to print

// Print the first N lines of the file


echo "First $N lines of the file:\n";
printFirstNLines($filename, $N);
echo "\n";

// Update/add content to the file


$newContent = "This is some new content...........\n";
updateFileContent($filename, $newContent);
echo "Content added to the file.\n";
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 18


Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 19
8. Develop a PHP program to read the content of the file and print the
frequency of occurrence of the word accepted by the user in the file
<?php

// Function to count the frequency of a word in a file

function countWordFrequency($filename, $word)


{
// Read the file contents into a string
$fileContents = file_get_contents($filename);

// Check if file reading was successful

if ($fileContents === false)


{
echo "Error reading the file.";
return;
}

// Convert the contents to lowercase to make the search case-insensitive


$fileContents = strtolower($fileContents);
$word = strtolower($word);

// Count the occurrences of the word


$wordCount = substr_count($fileContents, $word);

// Print the result


echo "The word '{$word}' occurs {$wordCount} times in the file.";
}

// Example usage
$filename =
C:\Users\AIML\Desktop\MY_PRAC_PHP\php_lab_programs\ple.txt"; // Specify
the path to your file
$word = "am"; // Replace with the word you want to search for
countWordFrequency ($filename, $word);
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 20


Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 21
9. Develop a PHP program to filter the elements of an array with key names.
Sample Input Data:
1st array: ('c1' => 'Red', 'c2' => 'Green', 'c3' => 'White', c4 => 'Black')
2nd array: ('c2', 'c4')

/*Develop a PHP program to filter the elements of an array with key names.
Sample Input Data:
1st array: ('c1' => 'Red', 'c2' => 'Green', 'c3' => 'White', c4 => 'Black')
2nd array: ('c2', 'c4') */

<?php

// Sample input data


$colors = [
'c1' => 'Red',
'c2' => 'Green',
'c3' => 'White',
'c4' => 'Black'
];

$keysToFilter = ['c2', 'c4'];

// Function to filter the array


function filterArrayByKeys($array, $keys) {
return array_filter($array, function($key) use ($keys) {
return in_array($key, $keys);
}, ARRAY_FILTER_USE_KEY);
}

// Filtering the colors array


$filteredColors = filterArrayByKeys($colors, $keysToFilter);

// Displaying the result


echo "Filtered Colors:\n";
print_r($filteredColors);

?>

Explanation of the Code

1.Input Data: We define two arrays: $colors, which is an associative array of


colors, and $keysToFilter, which contains the keys we want to filter.

2.Function Definition:

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 22


-->The filterArrayByKeys function takes two parameters: the array to be
filtered and the keys to filter by.
- ->Inside the function, array_filter is used with a callback function that checks if
- the current key exists in the $keys array using in_array.

4.Filtering the Array: We call the filterArrayByKeys function with the $colors
array and the $keysToFilter, storing the result in $filteredColors.

5.Output: Finally, we print the filtered array using print_r, which displays the
filtered colors.

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 23


10. Develop a PHP program that illustrates the concept of classes and
objects by reading and printing employee data, including Emp_Name,
Emp_ID, Emp_Dept, Emp_Salary, and Emp_DOJ.

<?php
Class Employee
{
// Properties
public $Emp_Name;
public $Emp_ID;
public $Emp_Dept;
public $Emp_Salary;
public $Emp_DOJ;

// Method to set employee data


public function setEmployeeData($name, $id, $dept, $salary, $doj)
{
$this->Emp_Name = $name;
$this->Emp_ID = $id;
$this->Emp_Dept = $dept;
$this->Emp_Salary = $salary;
$this->Emp_DOJ = $doj;
}
// Method to print employee data
public function printEmployeeData() {
echo "\n Employee Name: " . $this->Emp_Name . "\n";
echo "Employee ID: " . $this->Emp_ID . "\n";
echo "Employee Department: " . $this->Emp_Dept . "\n";
echo "Employee Salary: " . $this->Emp_Salary . "\n";
echo "Employee Date of Joining: " . $this->Emp_DOJ . "\n\n";
}
}
// Creating objects of the Employee class
$employee1 = new Employee ();
$employee2 = new Employee ();

// Setting employee data using the setEmployeeData method


$employee1->setEmployeeData("John Doe", 1001, "IT", 50000, "2022-01-01");
$employee2->setEmployeeData ("Jane Smith", 1002, "HR", 45000, "2023-05-
15");

// Printing employee data using the printEmployeeData method


$employee1->printEmployeeData();
$employee2->printEmployeeData();

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 24


?>
OUTPUT:

11. Develop
a. PHP program to count the occurrences of Aadhaar numbers present in a
text.
b. Develop a PHP program to find the occurrences of a given pattern and
replace them with a text.

11a.
<?php
function countAadhaarOccurrences($text) {
// Regular expression to match valid Aadhaar numbers
$pattern = "/\b[2-9][0-9]{3}\s[0-9]{4}\s[0-9]{4}\b/";

// Find all matches in the input text


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

// Count occurrences
return count($matches[0]);
}
// Example usage
$text = "Here are some Aadhaar numbers: 2347 5678 9412, 2345 6789 4333,
2256 7890 124";
$count = countAadhaarOccurrences($text);
echo "Number of valid Aadhaar numbers found: " . $count;
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 25


11 b. Develop a PHP program to find the occurrences of a given pattern and
replace them with a text

<?php
// Define the input string
$string = "\n The quick brown fox jumps over the lazy dog. The fox is clever.\n
\n ";

// Define the value to find (e.g., "fox")


$find = "fox";

// Define the replacement text


$replace = "cat";

// Replace all occurrences of the find value with the replace text
$new_string = str_replace($find, $replace, $string);

// Output the modified string


echo "\n $new_string";
?>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 26


12. Develop a PHP program to read the contents of a HTML form and
display the contents on a browser.
Form.html

<html>

<body>

<form action="display.php" method="POST">

Name: <input type="text" name="name"><br>

E-mail: <input type="text" name="email"><br>

<input type="submit">

</form>

</body>

</html>

SAVE File name as ----display.php

<html>

<body>

Welcome <?php echo $_GET["name"]; ?><br>

Your email address is: <?php echo $_GET["email"]; ?>

</body>

</html>

Praveen R, Asst Proff,Dept.of AIML,GMIT PHP-Lab-Manual 27

You might also like