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

PHP Pratical

The document contains 32 code snippets demonstrating various PHP concepts like: 1. Displaying text with echo 2. Calculating sums and averages 3. Concatenating strings 4. Swapping variable values 5. Conditional logic and comparisons 6. Loops to print patterns 7. Functions 8. Classes 9. Form handling 10. Date/time manipulation The snippets cover basic to intermediate PHP topics ranging from hello world programs to OOP concepts like classes and methods.

Uploaded by

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

PHP Pratical

The document contains 32 code snippets demonstrating various PHP concepts like: 1. Displaying text with echo 2. Calculating sums and averages 3. Concatenating strings 4. Swapping variable values 5. Conditional logic and comparisons 6. Loops to print patterns 7. Functions 8. Classes 9. Form handling 10. Date/time manipulation The snippets cover basic to intermediate PHP topics ranging from hello world programs to OOP concepts like classes and methods.

Uploaded by

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

1.

display hello world


Write a PHP Script that will display hello world

<?php
echo "Hello World";
?>

2. calculate sum
Write PHP script that will take three integer values for and calculate sum of it

<?php

$a = 3;
$b = 5;
$c = 10;

$sum = $a + $b + $c;

echo "The sum is" . $sum;

?>

3. calculate average of three values


In above PHP script calculate average of three values.

<?php

$a = 3;
$b = 5;
$c = 10;

$avg = ($a + $b + $c) / 3;

echo "The average is" . $avg;

?>

4. take two strings and concatenate it.


Write a PHP Script that will take two strings and concatenate it.

<?php

$string1 = "Hello";
$string2 = "World";

$concatenatedString = $string1 . $string2;

echo $concatenatedString;

?>
5. swap two integer values
Write a PHP Script that will assign two integer values and swap their values.

<?php

$int1 = 5;
$int2 = 8;

$temp = $int1;
$int1 = $int2;
$int2 = $temp;

echo $int1 . " " . $int2;

?>

6.swap two integer values without third variable.


Write PHP Script that will assign two integer values and swap their values without
third
variable.

<?php

$int1 = 5;
$int2 = 8;

$int1 += $int2;
$int2 = $int1 - $int2;
$int1 -= $int2;

echo $int1 . " " . $int2;

?>

7. perform arithmetic operations


Write a PHP Script that will assign two integer values that will perform arithmetic
operations
and display it in tabular format

<?php

$int1 = 5;
$int2 = 8;

echo "<table>";
echo "<tr>
<th>Operator</th>
<th>Result</th>
</tr>";
echo "<tr>
<td>$int1 + $int2</td>
<td>" . ($int1 + $int2) . "</td>
</tr>";
echo "<tr>
<td>$int1 - $int2</td>
<td>" . ($int1 - $int2) . "</td>
</tr>";
echo "<tr>
<td>$int1 x $int2</td>
<td>" . ($int1 * $int2) . "</td>
</tr>";
echo "<tr>
<td>$int1 / $int2</td>
<td>" . ($int1 / $int2) . "</td>
</tr>";
echo "</table>";

?>

8. two numbers and check their equality


Write a PHP Script that will assign two numbers and check their equality

<?php

$num1 = 5;
$num2 = 8;

if ($num1 == $num2) {
echo "The numbers are equal";
} else {
echo "The numbers are not equal";
}

?>

9. check they are identical or not


Write a PHP Script that will assign two numbers and check they are identical or not

<?php

$num1 = 5;
$num2 = 8;

if ($num1 === $num2) {


echo "The numbers are identical";
} else {
echo "The numbers are not identical";
}

?>

/+
10. check number is positive or negative
Write a PHP Script that will check number is positive or negative

<?php

$num = 8;
if ($num > 0) {
echo "The number is positive";
} elseif ($num < 0) {
echo "The number is negative";
} else {
echo "The number is zero";
}

?>

11. Even or Odd


Write a PHP Script that will check number is Even or Odd.

<?php

$num = 5;

if ($num % 2 == 0) {
echo "The number is even";
} else {
echo "The number is odd";
}

?>

12. check number is divisible by 13 and 7


Write a PHP Script that will check number is divisible by 13 and 7

<?php

$num = 91;

if ($num % 13 == 0 && $num % 7 == 0) {


echo "The number is divisible by both 13 and 7";
} else {
echo "The number is not divisible by both 13 and 7";
}

?>

13. Pattern
1
12
123
1234

<?php

for ($i = 1; $i <= 4; $i++) {


for ($j = 1; $j <= $i; $j++) {
echo $j;
}
echo "<br>";
}

?>

14. pattern
1
22
333
4444

<?php

for ($i = 1; $i <= 4; $i++) {


for ($j = 1; $j <= $i; $j++) {
echo $i;
}
echo "<br>";
}

?>

15. Pattern
1234
123
12
1

<?php

for ($i = 4; $i >= 1; $i--) {


for ($j = 1; $j <= $i; $j++) {
echo $j;
}
echo "<br>";
}

?>

16. pattern
4444
333
22
1

<?php

for ($i = 4; $i >= 1; $i--) {


for ($j = $i; $j >= 1; $j--) {
echo $i;
}
echo "<br>";
}
?>

17. nested for loop that creates a chess board


Write a PHP script using nested for loop that creates a chess board as shown below.

<?php

for($i = 1; $i <= 8; $i++) {


for($j = 1; $j <= 8; $j++) {
if(($i + $j) % 2 == 0) //For even row and column,
echo "\033[47m \033[0m"; //White color background
else
echo "\033[40m \033[0m"; //Black color background
}
echo "\n";
}
echo "\n";

?>

18. find out max number.


Write a PHP function that will take three integer values and find out max number.

<?php

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


{
if ($a >= $b && $a >= $c)
return $a;
else if ($b >= $a && $b >= $c)
return $b;
else
return $c;
}

?>

19. function that will take an integer value and return sum of digits.
Write a PHP function that will take an integer value and return sum of digits.

<?php

function sumOfDigits($n)
{
$sum = 0;
while ($n > 0)
{
$sum += $n % 10;
$n /= 10;
}
return $sum;
}
?>

20. calculate the factorial of a number


Write a function to calculate the factorial of a number (non-negative integer). The
function
accept the number as a argument

<?php

function factorial($n)
{
$res = 1;
for ($i = 2; $i <= $n; $i++)
$res *= $i;

return $res;
}

?>

21. check a number is prime or not


Write a PHP function to check a number is prime or not.

<?php

function isPrime($n)
{
if ($n <= 1) return false;
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;

return true;
}

?>

22. reverse a string.


Write a PHP function to reverse a string.

<?php

function reverseString($str)
{
$newString = "";
for ($i = strlen($str) - 1; $i >= 0; $i--)
$newString .= $str[$i];

return $newString;
}

?>
23. function that checks whether a passed string is palindrome or not
Write a PHP function that checks whether a passed string is palindrome or not?

<?php

function isPalindrome($str)
{
$i = 0;
$j = strlen($str) - 1;

while ($i < $j) {


if ($str[$i] != $str[$j])
return false;

$i++;
$j--;
}
return true;
}

?>

24. simple PHP class which displays the following string : 'MyClass class has
initialized !'
Write a simple PHP class which displays the following string : 'MyClass class has
initialized
!'

<?php

class MyClass
{
public function __construct()
{
echo 'MyClass class has initialized!';
}
}

?>

25. simple PHP class which displays an introductory message


Write a simple PHP class which displays an introductory message like "Hello All, I
am
ALKA", where "ALKA" is an argument value of the method within the class.

<?php

class MyClass
{
public function __construct($name)
{
echo "Hello All, I am $name";
}
}

?>

26. sorts an ordered integer array


Write a PHP class that sorts an ordered integer array with the help of sort()
function

<?php

class ArraySorter
{
public function sort($arr)
{
sort($arr);
return $arr;
}
}

?>

27. PHP Calculator


Write a PHP Calculator class which will accept two values as arguments, then add
them,
subtract them, multiply them together, or divide them on request.

<?php

class Calculator
{
public function __construct($x, $y)
{
$this->x = $x;
$this->y = $y;
}

public function add()


{
return $this->x + $this->y;
}

public function subtract()


{
return $this->x - $this->y;
}

public function multiply()


{
return $this->x * $this->y;
}

public function divide()


{
return $this->x / $this->y;
}
}

?>

28. Calculate the difference between two dates using PHP OOP approach.
Calculate the difference between two dates using PHP OOP approach.
Sample Dates : 1981-11-03, 2013-09-04
Expected Result : Difference : 31 years, 10 months, 1 days

<?php

class DateDifference
{
public function calculateDifference($date1, $date2)
{
$date1 = new DateTime($date1);
$date2 = new DateTime($date2);

$difference = $date2->diff($date1);
$years = $difference->y;
$months = $difference->m;
$days = $difference->d;

return "Difference : $years years, $months months, $days days";


}
}

?>

29. convert string to Date and DateTime


Write a PHP script to convert string to Date and DateTime.
Sample Date : '12-08-2004'
Expected Output : 2004-12-08
Note : PHP considers '/' to mean m/d/Y format and '-' to mean d-m-Y format.

<?php

// Convert string to date


$date = DateTime::createFromFormat('d-m-Y', '12-08-2004');
$date = $date->format('Y-m-d');

// Convert string to datetime


$dateTime = DateTime::createFromFormat('d-m-Y', '12-08-2004');
$dateTime = $dateTime->format('Y-m-d H:i:s');

?>

30. take name and message from user and display it.
Write a HTML Form & PHP Script that will take name and message from user and
display it.

<html>
<head>
<title>Name & Message Form</title>
</head>
<body>
<form action="displayMessage.php" method="post">
<label for="name">Name: </label>
<input type="text" name="name" />

<label for="message">Message: </label>


<input type="text" name="message" />

<input type="submit" />


</form>
</body>
</html>

<?php

if(isset($_POST['name']) && isset($_POST['message'])){


$name = $_POST['name'];
$message = $_POST['message'];

echo "Name: ".$name."<br />";


echo "Message: ".$message."<br />";
}

?>

31. guessing game,


Write a PHP Script for guessing game,which will take one number from user and check
that
number is right or wrong

<?php

$secretNumber = 7; // the secret number for the guessing game

if(isset($_POST['guess'])){
$guess = $_POST['guess'];

if($guess == $secretNumber){
echo "You guessed correctly!";
} else {
echo "Your guess was incorrect. The correct answer was ".$secretNumber.".";
}
}

?>

32. count the number of guessing attempts using hidden fields


In above PHP Script count the number of guessing attempts using hidden fields.

<?php

$secretNumber = 7; // the secret number for the guessing game


$attempts = 0; // variable to count the number of attempts taken

if(isset($_POST['guess'])){
$guess = $_POST['guess'];
$attempts = $_POST['attempts'];

if($guess == $secretNumber){
echo "You guessed correctly!";
} else {
$attempts = $attempts + 1;
echo "Your guess was incorrect. The correct answer was ".$secretNumber.".";
}
}

// add a hidden field to the form to store the number of attempts


echo "<input type='hidden' name='attempts' value='".$attempts."'>";

?>

33. displays the marksheet of the student.


Write a php page and create a user form which asks for marks in five subjects out
of 100
and
then displays the marksheet of the student. The format is as follows:
Name of Student*:
Marks in Each Subject
Subject 1* :
Subject 2* :
Subject 3* :
Subject 4* :
Subject 5* :
Total Marks Obtained:
Total Marks:
‡
Note: All the entries marked (*) are to be input by the user. And use a submit
button to post
the
entries in the form using the POST method.
1. Write a php page and create a user form which asks for marks in five subjects
out of
100 and
then displays the marksheet of the student. The format is as follows:
Name of Student*:
Marks in Each Subject
Subject 1* :
Subject 2* :
Subject 3* :
Subject 4* :
Subject 5* :
Total Marks Obtained:
Total Marks:
‡
Note: All the entries marked (*) are to be input by the user. And use a submit
button to post
the
entries in the form using the POST method.
<?php

if (isset($_POST['submit'])) {
// collect the user input
$name = $_POST['name'];
$subject1 = $_POST['subject1'];
$subject2 = $_POST['subject2'];
$subject3 = $_POST['subject3'];
$subject4 = $_POST['subject4'];
$subject5 = $_POST['subject5'];
$totalMarksObtained = $subject1 + $subject2 + $subject3 + $subject4 +
$subject5;
$totalMarks = 500;

// generate the marksheet


echo "Marksheet";
echo "<br>Name of Student: $name";
echo "<br>Marks in Each Subject";
echo "<br>Subject 1: $subject1";
echo "<br>Subject 2: $subject2";
echo "<br>Subject 3: $subject3";
echo "<br>Subject 4: $subject4";
echo "<br>Subject 5: $subject5";
echo "<br>Total Marks Obtained: $totalMarksObtained";
echo "<br>Total Marks: $totalMarks";
}

?>

<!-- Create the form -->


<form action="" method="POST">
Name of Student*: <input type="text" name="name">
<br><br>Marks in Each Subject
<br>Subject 1* : <input type="text" name="subject1">
<br>Subject 2* : <input type="text" name="subject2">
<br>Subject 3* : <input type="text" name="subject3">
<br>Subject 4* : <input type="text" name="subject4">
<br>Subject 5* : <input type="text" name="subject5">
<br><br><input type="submit" name="submit" value="Submit">
</form>

34. send mail


Write a PHP Script that will be used for mail send.

<?php

// Retrieve the form data


$to = $_POST['to'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: [email protected]";

// Send the mail


mail($to, $subject, $message, $headers);

?>
<!-- Create the form -->
<form action="" method="POST">
To: <input type="text" name="to">
<br><br>Subject: <input type="text" name="subject">
<br><br>Message:<br><textarea name="message" rows="10" cols="50"></textarea>
<br><br><input type="submit" value="Send Mail">
</form>

35. upload a file.


Write a php script that will help to upload a file.

<?php

// Check if the form is submitted


if (isset($_POST['submit'])) {
// Retrieve the file
$file = $_FILES['file'];

// Get file details


$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

// Get the file extension


$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

// Allowed file types


$allowedExt = array('jpg', 'jpeg', 'png', 'pdf');

// Check if the file type is allowed


if (in_array($fileActualExt, $allowedExt)) {
// Check for errors
if ($fileError === 0) {
// Check for file size
if ($fileSize < 1000000) {
// Create a new name for the file
$fileNameNew = uniqid('' ,true).".".$fileActualExt;

// Define the file path


$fileDestination = 'uploads/'.$fileNameNew;

// Move the file to the specified directory


move_uploaded_file($fileTmpName, $fileDestination);

// Redirect the user


header("Location: index.php?uploadsuccess");
} else {
echo "Your file is too big!";
}
} else {
echo "There was an error uploading your file!";
}
} else {
echo "You cannot upload files of this type!";
}

?>

<!-- Create the form -->


<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<br><br><input type="submit" name="submit" value="Upload File">
</form>

36. create an IMCA database


Write a PHP that will create an IMCA database.

<?php

// Create database connection


$conn = mysqli_connect('localhost', 'username', 'password');

// Check the connection


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

// Create the database


$sql = "CREATE DATABASE imca";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

// Close the connection


$conn->close();

?>

37. create sem_5 table under IMCA Database


Write a PHP Script that will create sem_5 table under IMCA Database

<?php

// Create database connection


$conn = mysqli_connect('localhost', 'username', 'password', 'imca');

// Check the connection


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

// Create the sem_5 table


$sql = "CREATE TABLE sem_5 (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
subject VARCHAR(50) NOT NULL,
grade INT(2)
)";

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


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

// Close the connection


$conn->close();

?>

38. insert data into sem_5 table.


Write a PHP Script that will insert data into sem_5 table.

<?php

// Create database connection


$conn = mysqli_connect('localhost', 'username', 'password', 'imca');

// Check the connection


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

// Insert data into sem_5 table


$sql = "INSERT INTO sem_5 (subject, grade)
VALUES ('Math', 3),
('English', 4),
('History', 5),
('Science', 4),
('Computer Science', 5)";

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


echo "Data inserted successfully into sem_5 table";
} else {
echo "Error inserting data into sem_5 table: " . $conn->error;
}

// Close the connection


$conn->close();

?>

39. display records of sem5 table in tabular format.


Write a PHP Script that will display records of sem5 table in tabular format.

<?php

// Create database connection


$conn = mysqli_connect('localhost', 'username', 'password', 'imca');

// Check the connection


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

// Select all records from sem_5 table


$sql = "SELECT * FROM sem_5";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table>";
echo "<tr><th>ID</th><th>Subject</th><th>Grade</th></tr>";
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["subject"]."</td><td>".
$row["grade"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

// Close the connection


$conn->close();

?>

40. delete records from sem_5 table.


Write a PHP Script that will delete records from sem_5 table.

<?php

// Create database connection


$conn = mysqli_connect('localhost', 'username', 'password', 'imca');

// Check the connection


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

// Delete records from sem_5 table


$sql = "DELETE FROM sem_5 WHERE grade = 3";

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


echo "Records deleted successfully from sem_5 table";
} else {
echo "Error deleting records from sem_5 table: " . $conn->error;
}

// Close the connection


$conn->close();

?>

41. drop table sem_5 from database


Write a PHP Script that will drop table sem_5 from database.
<?php

// Create database connection


$conn = mysqli_connect('localhost', 'username', 'password', 'imca');

// Check the connection


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

// Drop sem_5 table


$sql = "DROP TABLE sem_5";

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


echo "Table sem_5 dropped successfully";
} else {
echo "Error dropping the sem_5 table: " . $conn->error;
}

// Close the connection


$conn->close();

?>

42. load content from text file using ajax.


Write a PHP Script that will load content from text file using ajax.

<?php

$file = 'data.txt';

if(file_exists($file)){
$data = file_get_contents($file);
echo json_encode($data);
}

?>

<script>
$.ajax({
type: 'GET',
url: 'data.php',
dataType: 'json',
success: function(data){
// Do something with the returned data
console.log(data);
}
});
</script>

43. suggest namelist to user on key enter event using ajax


Write a PHP Script that will suggest namelist to user on key enter event using
ajax.
<?php

$names = array('John', 'Jane', 'Jack', 'Jill', 'Jim', 'Joan');

if(isset($_GET['term'])){
$term = $_GET['term'];

$list = array();

foreach($names as $name){
if(stristr($name, $term)){
$list[] = $name;
}
}

echo json_encode($list);
}

?>

<script>
$('#name').keyup(function(){
var term = $(this).val();

$.ajax({
type: 'GET',
url: 'names.php',
data: {
term: term
},
dataType: 'json',
success: function(data){
// Do something with the returned data
console.log(data);
}
});
});
</script>

44. display employee information on selection of name using ajax.


Write a PHP Script that will display employee information on selection of name
using ajax.

<?php

$employees = array(
array('name' => 'John', 'age' => '30', 'role' => 'Manager'),
array('name' => 'Jane', 'age' => '25', 'role' => 'Developer'),
array('name' => 'Jack', 'age' => '27', 'role' => 'Designer')
);

if(isset($_GET['name'])){
$name = $_GET['name'];

foreach($employees as $employee){
if($employee['name'] == $name){
echo json_encode($employee);
break;
}
}
}

?>

<script>
$('#names').change(function(){
var name = $(this).val();

$.ajax({
type: 'GET',
url: 'employees.php',
data: {
name: name
},
dataType: 'json',
success: function(data){
// Do something with the returned data
console.log(data);
}
});
});
</script>

46. jquery code that hide / show text on button click event
Write a jquery code that hide / show text on button click event.

47. jquery code that will fade in, fade out,fade toggle images on click event
Write a jquery code that will fade in, fade out,fade toggle images on click event.

48. slide up, slide down and slide togle panel on click event.
Write a jquery code that will slide up, slide down and slide togle panel on click
event.

You might also like