[go: up one dir, main page]

0% found this document useful (0 votes)
2K views34 pages

PHP Practical File

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 34

Name: - Love Shah

Enrollment No: - IU2082820066


BRANCH: - IMCA
Subject: - Php
Faculty Name :- Mansi Mam

PHP PRACTICAL FILE


Q-1 Write a php script to display a welcome message to the user using html tags

CODE :-
<!DOCTYPE html>
<html>
<body>

<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

</body>
</html>

Q-2 Create a variable $var = 'PHP Tutorial'. Display this variable using <h3> tag with
the following content under this heading:
PHP Tutorial
PHP, an acronym for Hypertext Preprocessor, is a widely-used open source general-
purpose scripting language. It is a cross-platform, HTML embedded server-side
scripting language and is especially suited for web development.

Code :-
<?php
/*Create a variable $var = 'PHP Tutorial'. Display this variable using <h3> tag with the following
content under this heading:
PHP Tutorial
PHP, an acronym for Hypertext Preprocessor, is a widely-used open source general-purpose
scripting language. It is a cross-platform, HTML embedded server-side scripting language and is
especially suited for web development.*/

echo "<html>";
echo "<head>";
echo "<title>";
echo "PHP TUTORIAl";
echo "</title>";
echo "<body>";
echo "<h3>PHP TUTORIAL</h3>";
echo "<hr>";
echo "<p>PHP, an acronym for Hypertext Preprocessor, is a widely-used open source general-
purpose scripting language.<br> It is a cross-platform, HTML embedded server-side scripting
language and is especially suited for web development.</p>";
echo "</body>";
echo "</head>";
echo "</html>";
?>

Q-3 Write a php script to perform addition and subtraction of two numbers

CODE :-
<?php
/*Write a php script to perform addition and subtraction of two numbers*/
$x = 10;
$y = 6;

echo $x + $y;
?>

Q-4 Create a php script to perform the arithmetic operation of a float value with an integer value.

CODE
<?php
// Create a php script to perform the arithmetic operation of a float value with an integer value.
$x=100;
$y=60;
echo "Division of x and y : ". ($x/$y) ."<br />";
?>
Q-5 Write a program to print the following, using two php variables and a single echo
statement. Also apply HTML formatting tags
Output: Good Morning. Have a 'Nice' day.

CODE :- <?php
$message_1 = "Good Morning.";
$message_2 = "Have a nice day!";
echo $message_1." ". $message_2;
?>

Q-6 Write a php script to print whether a number is even or odd using boolean data-type.

CODE:-

<?php
$var=10;
var_dump($var>10);
var_dump($var==true);
?>

7. Write a PHP program to convert word to digit.


<?php
function word_digit($word) {
$warr = explode(';',$word);
$result = '';
foreach($warr as $value){
switch(trim($value)){
case 'zero':
$result .= '0';
break;
case 'one':
$result .= '1';
break;
case 'two':
$result .= '2';
break;
case 'three':
$result .= '3';
break;
case 'four':
$result .= '4';
break;
case 'five':
$result .= '5';
break;
case 'six':
$result .= '6';
break;
case 'seven':
$result .= '7';
break;
case 'eight':
$result .= '8';
break;
case 'nine':
$result .= '9';
break;
}
}
return $result;
}

echo word_digit("zero;three;five;six;eight;one")."\n";
echo word_digit("seven;zero;one")."\n";
?>

Output :-

8. Write a php script to store and display the Enrollment number and Name of 5
students in tabular format.

Code :-
<html>

<h2>T4Tutorials.com</h2>
<h3>Form program</h3>
<p>show output student name and roll number</p>
</html>
<html>
<body>
<form method="post">
<p>Enter Name</p>
<input type="text" name="name" />
<p>Enter Roll number</p>
<input type="text" name="number" />
<input type="submit" name="submit" />
</form>
<?php
class student
{
public $name= 'ali';
public $rno=77;
}
$a = new student();
if(isset($_POST['submit'])){
$a->name=$_POST['name'];
$a->rno=$_POST['number'];
echo"Name of student= $a->name</h2><br>";
echo"Roll number of student= $a->rno</h2>";
}
?>
</body>
</html>

9. Write a PHP script using a loop to add all the prime numbers between 0 and 30 and
display the sum

Code :-
<?php
$sum = 0;
for($x=1; $x<=30; $x++)
{
$sum +=$x;
}
echo "The sum of the numbers 0 to 30 is $sum"."\n";
?>

10. Write a PHP script which displays all the numbers between 0 and 150 that are
divisible by 3.

Code :-
<?php
// PHP program to print all the numbers
// divisible by 3 and 5 for a given number

// Result function with N


function result($N)
{
// iterate from 0 to N
for ($num = 0; $num < $N; $num++)
{
// Short-circuit operator is used
if ($num % 3 == 0 && $num % 5 == 0)
echo $num, " ";
}
}

// Driver code

// input goes here


$N = 100;

// Calling function
result($N);

// This code is contributed by ajit


?>
11. Write a PHP script to create a simple calculator using a switch case

Code :-
<!DOCTYPE html>
<head>
<title>Simple Calculator Program in PHP - Tutorials Class</title>
</head>
<?php $first_num = $_POST['first_num']; $second_num = $_POST['second_num']; $operator =
$_POST['operator'];
$result = ''; if (is_numeric($first_num) && is_numeric($second_num))
{ switch ($operator)
{ case "Add": $result = $first_num + $second_num; break; case "Subtract": $result = $first_num -
$second_num; break;
case "Multiply": $result = $first_num * $second_num;
break; case "Divide": $result = $first_num / $second_num;
} } ?>
<body>
<div id="page-wrap">
<h1>PHP - Simple Calculator Program</h1>
<form action="" method="post" id="quiz-form">
<p> <input type="number" name="first_num" id="first_num" required="required" value="<?php
echo $first_num; ?>" />
<b>First Number</b>
</p>
<p> <input type="number" name="second_num" id="second_num" required="required"
value="<?php echo $second_num; ?>" />
<b>Second Number</b>
</p> <p> <input readonly="readonly" name="result" value="<?php echo $result; ?>">
<b>Result</b> </p> <input type="submit" name="operator" value="Add" /> <input
type="submit" name="operator" value="Subtract" /> <input type="submit" name="operator"
value="Multiply" /> <input type="submit" name="operator" value="Divide" /> </form>
</div> </body> </html>

12. Write a php script to print the following pyramid:

Code :-
<?php
for($i=0;$i<=5;$i++)
{
for($j=5-$i;$j>=0;$j--){
echo "*";
}
echo "<br>";
}
?>
13.Write a php script to print the following pyramid:

Code :-
<?php $n = 5;
for ($i= 1; $i <= $n; $i++)
{
echo " ";
$mid = (2 * $i) - 1;
for (
$j = 1;
$j <=($n - $i);
$j++
) echo " ";
for ($j = $i;
$j<= $mid;
$j++
) echo $j;
for ($k = ($mid - 1);
$k >= $i;
$k--)
echo $k ;
echo "\n";
}
?>
14. Write a choice-based PHP script to perform the following:
1. Find length of a string
2. transform a string to all uppercase letters.
3. transform a string to all lowercase letters.
4. make a string's first character uppercase.
5. make a string's first character of all the words uppercase.

Code: <?php
$str = "hello world!";
echo "<h3>Length of string : ".strlen($str)."</h3>";
echo "<h3>String in Upper case : ".strtoupper($str)."</h3>";
echo "<h3>String in Upper case : ".strtolower($str)."</h3>";
echo "<h3>String's first character in Uppercase : ".ucfirst($str)."</h3>";
echo "<h3>String's first character of all words Uppercase : ".ucwords($str)."</h3>";
?>

15. Write a PHP script to check whether a string contains a specific string or
not? Sample string: 'The quick brown fox jumps over the lazy dog.'
Check whether the said string contains the string 'jumps'.
Code:
<?php
$str='The quick brown fox jumps over the lazy dog';
$string_find='jumps';
echo "String : $str<br>";
if(strstr($str,$string_find))
{
echo"<br>'$string_find' is present in the about string <br>";
}
Else
echo"$string_fing is not present in the given string ";
?>

16. Write a PHP program to reverse a given string.


Code: <?php
$str = "Hello World!";
echo "String : $str";
echo "<br>Reverse String : ".strrev($str);
?>
17. Write a PHP script to extract the user name from the following email ID.
Sample String : 'rayy@example.com'
Expected Output : 'rayy'

Code:
<?php
$str = "rayy@example.php";
echo (substr($str,0,4));
?>

18. Write a PHP script to replace the first 'the' of the following string with 'That'.
Sample date : 'the quick brown fox jumps over the lazy dog.'
Expected Result : That quick brown fox jumps over the lazy dog..

Code:
<?php
$str = "String : the quick brown fox jumps over the lazy dog<br>";
echo "$str";
echo "<br>Replace the first 'the' of the following string with 'That'<br>";
$str_replace = substr_replace($str,"That",0,3);
echo "<br>New String : $str_replace";
?>
19. Write a PHP script to insert a string at the specified position in a given string.
Original String : 'The brown fox'
Insert 'quick' between 'The' and 'brown'.
Expected Output : 'The quick brown fox'

Code:
<?php
$str="The brown fox";
echo "Original String : $str<br><br>";
echo "Insert 'quick' between 'The' and 'brown'<br><br>";
$string_replace= substr_replace($str,"quick ",4,-9);
echo "Output : $string_replace";
?>

20. Write a php script to print an array.


Code:

<?php
$fruits_arr = array("Mango","Apple","Grapes","Orange");
echo "<pre>";
print_r($fruits_arr);
echo "</pre>";
?>

21. Write PHP program to find number of elements in an array

Code:
<?php
$fruits_arr = array("Mango","Apple","Grapes","Orange");
$total_elements=count($fruits_arr);
echo "<pre>";
print_r($fruits_arr);
echo "</pre>";
echo "There are $total_elements elements in array.";
?>
22. Write a PHP script to sort elements in an array in descending order.

Code:
<?php
$arr=[3,12,6,5,55,28];
rsort($arr);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

23. Write a PHP script to split a string as array elements based on delimiter.
Code: <?php
$str = "This,is,a,PHP,Program.";
$str1 =preg_split("/,/",$str);
echo "<pre>";
print_r($str1);
echo "</pre>";
?>
24. Write a PHP program to combine the array elements into a string with a given
delimiter.

Code:

<?php
$arr = array('This','is','a','PHP','program.');
echo implode(" ",$arr);
?>

25.Create a form to accept Username and electricity units consumed. You need to write a PHP
script to calculate the electricity bill using if-else conditions.
Conditions:
For first 50 units – Rs. 3.50/unit
For next 100 units – Rs. 4.00/unit
For next 100 units – Rs. 5.20/unit
For units above 250 – Rs. 6.50/unit
Display the bill amount along with the username. Use HTML formatting tags.

Code: -
<html>
<head>
<title>Electricity Units Calculator</title>
</head>
<form method="post">
<table>
<tr>
<td>
Username:
</td>
<td>
<input type="text" name="username" placeholder="Enter your username"
value=""> </td>
</tr>
<tr>
<td>
Units:
</td>
<td>
<input type="text" name="units" placeholder="Enter amount of units"
value="">
</td>
</tr>
</table>
<input type="submit" name="subbtn" value="Calculate!">
</form>
</html>
<?php
if(isset($_POST['subbtn']))
{
$username = $_POST['username'];
$units = $_POST['units'];
if(empty($username))
{
echo "Enter a username";
}
elseif(empty($units))
{
echo "Enter units first!";
}
Else
{
if ($units <= 50)
{
$ans = $units*3.50;
echo "Username: $username<br>";
echo "Units entered: $units<br>";
echo " Bill amount is :$ans";
}
elseif ($units >=50 && $units <=150)
{
$ans = $units*4.00;
echo "Username: $username<br>";
echo "Units entered: $units<br>";
echo "Bill Amount is: $ans";
}
elseif ($units >=150 && $units <=250)
{
$ans= $units*5.20;
echo "Username: $username<br>";
echo "Units entered: $units<br>";
echo "Bill amount is: $ans";
}
elseif ($units >=250)
{
$ans = $units*6.50;
echo "Username: $username<br>";
echo "Units entered: $units<br>";
echo "Bill amount is:$ans";
}
}
}
?>

26.Create a form to accept the day number of the week (1-7) and display the day of the week. Eg if
user inputs: 1
output: “Sunday”
Code:
<html>
<head><title>Form</title></head>
<body>
<form method="post">
<input type="text" name="num" placeholder="Enter Number">
<input type="submit" name="submitBtn" value="Submit">
</form>
</body>
<?php

if(isset($_POST['num'])){
$Num=$_POST['num'];
switch($Num)
{
case 1:
echo "Sunday";
break;
case 2:
echo "Monday";
break;
case 3:
echo "Tuesday";
break;
case 4:
echo "Wadnesday";
break;
case 5:
echo "Thursday";
break;
case 6:
echo "Friday";
break;
case 7:
echo "Saturday";
break;
default:
echo "Enter valid Number";
break;
}

}
?>
</html>
27.Create a form to accept a numeric value from the user. Write a PHP program to calculate the
factorial of a number.
Code:
<html>
<head><title>Form</title></head>
<body>
<form method="post">
<input type="text" name="num" placeholder="Enter Number">
<input type="submit" name="submitBtn" value="Submit">
</form>
</body>
<?php
if(isset($_POST['num'])){
$Num = $_POST['num'];
if(empty($Num)){
echo "Enter valid number";
}
else{
$factorial=1;
for($a=$Num;$a>=1;$a--){
$factorial=$factorial*$a;
}
echo "Factorial of $Num is $factorial.";
}
}
?>
</html>

28.Create a form of a simple calculator program in PHP using switch-case.

Code:
<html>
<head><title>Calculator</title></head>
<?php
$Num1=$_POST['firstNum'];
$Num2=$_POST['secondNum'];
$operator=$_POST['operator'];
$res='';

if(isset($Num1)&&isset($Num2)){
switch($operator){
case "Add":
$res = $Num1 + $Num2;
break;
case "Subtract":
$res = $Num1 - $Num2;
break;
case "Multiply":
$res = $Num1 * $Num2;
break;
case "Divide":
$res = $Num1 / $Num2;
break;
default:
echo "Choose valid option.";
}
}

?>
<body>
<form method="post">
<input type="number" name="firstNum"
value="<?php echo $Num1; ?>"> First Number<br><br>
<input type="number" name="secondNum" value="<?php echo $Num2; ?>">
Second Number<br><br>
<input readonly="readonly" name="result" value="<?php echo $res; ?>">
Result<br><br>
<input type="submit" name="operator" value="Add">
<input type="submit" name="operator" value="Subtract">
<input type="submit" name="operator" value="Multiply">
<input type="submit" name="operator" value="Divide">
</form>
</body>

</html>
29.Create a HTML webpage to accept username, password and contact number from the user.
Write a php script to validate the following using regular expressions as follows:
a. Username: min 5 characters(alphanumeric), max 20 characters(alphanumeric), only _ and
@ allowed.
b. Password: min 5 characters(alphanumeric), max 20 characters(alphanumeric), must have
min one capital letter and one special character.
c. Contact Number: 10 digit contact number.

Code:
<html>
<head><title>Form</title></head>
<body>
<form method="post">

<table>
<tr>
<td><label>Username</label></td>
<td><input type="text" name="username"></td>
</tr>

<tr>
<td><label>Password</label></td>
<td><input type="password" name="passwd"></td>
</tr>

<tr>
<td><label>Phone Number</label></td>
<td><input type="tel" name="phoneNum"></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitBtn" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>

30.Write a PHP script to create and display any associative array having Country names
and their capitals as key-value pairs. Add a minimum 7 key-value pairs in the array.
Code:
<?php
$arr=array(
"India"=>"New Delhi",
"France"=>"Paris",
"Germany"=>"Berlin",
"Ireland"=>"Dublin",
"Spain"=>"Madrid",
"United Kingdom"=>"London",
"Finland"=>"Helsinki"
);

echo "<pre>";
print_r($arr);
echo "</pre>";
?>
31.Write a PHP script to create an array to store the employee name (key) and their salary
(value), of 5 employees, in an associative array. Create a HTML page to provide the
following options to the user:
a. Display an array
b. Sort an array based on Key
c. Sort an array based on Value
d. Sort an array based on Key in reverse
e. Sort an array based on Value in reverse
Code:
<html>
<head><title>Program 10</title></head>
<body>
<h3>Choice:-</h3>
<h3>a. Display an array.</h3>
<h3>b. Sort an array based on key.</h3>
<h3>c. Sort an array based on value.</h3>
<h3>d. Sort an array based on key in reverse.</h3>
<h3>e. Sort an array based on value in reverse.</h3>
<form method="post">
<table>
<tr>
<td><label>Enter Choice:</label></td>
<td><input type="text" name="choice"></td>
</tr>
</table>
<input type="submit" value="Submit" name="submitBtn">
</form>
</body>
</html>
<?php

$arr=array(
"ABC"=>50000,
"DEF"=>45000,
"GHI"=>30000,
"JKL"=>35000,
"MNO"=>28000,
);

if(isset($_POST['submitBtn'])){
if(!empty($_POST['choice'])){
switch($_POST['choice']){
case 'a':
echo "<pre>";
print_r($arr);
echo "</pre>";
break;

case 'b':
echo "<pre>";
ksort($arr);
print_r($arr);
echo "</pre>";
break;

case 'c':
echo "<pre>";
asort($arr);
print_r($arr);
echo "</pre>";
break;

case 'd':
echo "<pre>";
krsort($arr);
print_r($arr);
echo "</pre>";
break;

case 'e':
echo "<pre>";
arsort($arr);
print_r($arr);
echo "</pre>";
break;

default:
echo "Enter valid choice.";
break;
}
}
}
?>
32. Create a multidimensional array to store details of 5 students in the following
format:
allStudents -> Student1 -> stud_detail(name, email)
-> subjects (sub_name -> marks, key value pair for 3
subjects)
<?php
$marks = array(
"love" => array(
"C" => 95,
"C++" => 85,
"FODBMS" => 74,
),
"vidhi" => array(
"C" => 78,
"C++" => 98,
"FODBMS" => 46,
),
"hetvi" => array(
"C" => 88,
"C++" => 46,
"FODBMS" => 99,
),
);
echo $marks['hetvi']['C'] . "\n";
foreach($marks as $mark) {
echo $mark['C']. " ".$mark['C++']." ".$mark['FODBMS']."\n";
}
?>
33.Write a PHP script to demonstrate the use of following array functions:
1. array_diff()
2. array_merge()
3. array_intersect()
4. array_shift()
5. array_unshift()
6. array_flip()

<?php
$a1=array(1=>"red",2=>"blue",3=>"green");
$a2=array(4=>"yellow",5=>"blue");
echo("a.");
print_r(array_diff($a1,$a2));
echo("<br>");
echo("b.");
print_r(array_merge($a1,$a2));
echo("<br>");
echo("c.");
print_r(array_intersect($a1,$a2));
echo("<br>");
echo("d.");
echo array_shift($a1);
print_r ($a1);
echo("<br>");

echo("e.");
array_unshift($a1,"orange");
print_r($a1);
echo("<br>");
echo("f.");
print_r(array_flip($a1));
echo("<br>");
?>
34.Write a PHP script to print the date in this format: 16th of August 2021 11:14:45
AM
Code:-

<!DOCTYPE html>
<html>
<body>

<?php
$date=date_create("2021-08-16");
echo date_format($date,"16-F-11:14:15");
?>

</body>
</html>

35.Write a PHP script to calculate the current age of a person.


<?php
$bday = new DateTime('04.08.2001');
$today = new Datetime(date('m.d.y'));
$diff = $today->diff($bday);
printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
printf("\n");
?>

36.Create a HTML page to accept a value from the user and list of Maths functions to
select from. Apply the appropriate math function using php script and display
formatted output to the user.

CODE:-

<!DOCTYPE html>
<html>

<head>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.6.4/math.js"
integrity=
"sha512-
BbVEDjbqdN3Eow8+empLMrJlxXRj5nEitiCAK5A1pUr66+jLVejo3PmjIaucRnjlB0P9R3rBUs3g5jXc8ti+fQ
=="
crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.6.4/math.min.js"
integrity=
"sha512-
iphNRh6dPbeuPGIrQbCdbBF/qcqadKWLa35YPVfMZMHBSI6PLJh1om2xCTWhpVpmUyb4IvVS9iYnnY
MkleVXLA=="
crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
<!-- for styling -->
<style>
table {
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}

input[type="button"] {
width: 100%;
padding: 20px 40px;
background-color: green;
color: white;
font-size: 24px;
font-weight: bold;
border: none;
border-radius: 5px;
}

input[type="text"] {
padding: 20px 30px;
font-size: 24px;
font-weight: bold;
border: none;
border-radius: 5px;
border: 2px solid black;
}
</style>
</head>
<!-- create table -->

<body>
<table id="calcu">
<tr>
<td colspan="3"><input type="text" id="result"></td>
<!-- clr() function will call clr to clear all value -->
<td><input type="button" value="c" onclick="clr()" /> </td>
</tr>
<tr>
<!-- create button and assign value to each button -->
<!-- dis("1") will call function dis to display value -->
<td><input type="button" value="1" onclick="dis('1')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="2" onclick="dis('2')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="3" onclick="dis('3')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="/" onclick="dis('/')"
onkeydown="myFunction(event)"> </td>
</tr>
<tr>
<td><input type="button" value="4" onclick="dis('4')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="5" onclick="dis('5')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="6" onclick="dis('6')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="*" onclick="dis('*')"
onkeydown="myFunction(event)"> </td>
</tr>
<tr>
<td><input type="button" value="7" onclick="dis('7')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="8" onclick="dis('8')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="9" onclick="dis('9')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="-" onclick="dis('-')"
onkeydown="myFunction(event)"> </td>
</tr>
<tr>
<td><input type="button" value="0" onclick="dis('0')"
onkeydown="myFunction(event)"> </td>
<td><input type="button" value="." onclick="dis('.')"
onkeydown="myFunction(event)"> </td>
<!-- solve function call function solve to evaluate value -->
<td><input type="button" value="=" onclick="solve()"> </td>

<td><input type="button" value="+" onclick="dis('+')"


onkeydown="myFunction(event)"> </td>
</tr>
</table>

<script>
// Function that display value
function dis(val) {
document.getElementById("result").value += val
}

function myFunction(event) {
if (event.key == '0' || event.key == '1'
|| event.key == '2' || event.key == '3'
|| event.key == '4' || event.key == '5'
|| event.key == '6' || event.key == '7'
|| event.key == '8' || event.key == '9'
|| event.key == '+' || event.key == '-'
|| event.key == '*' || event.key == '/')
document.getElementById("result").value += event.key;
}

var cal = document.getElementById("calcu");


cal.onkeyup = function (event) {
if (event.keyCode === 13) {
console.log("Enter");
let x = document.getElementById("result").value
console.log(x);
solve();
}
}

// Function that evaluates the digit and return result


function solve() {
let x = document.getElementById("result").value
let y = math.evaluate(x)
document.getElementById("result").value = y
}

// Function that clear the display


function clr() {
document.getElementById("result").value = ""
}
</script>
</body>

</html>

You might also like