0% found this document useful (0 votes)
18 views21 pages

PHP Programming Examples and Patterns

The document contains various PHP programming exercises demonstrating the use of conditional statements, loops, arrays, string functions, and object-oriented concepts. It includes examples of creating and manipulating indexed and associative arrays, implementing inheritance, and building a simple registration form. Each section provides code snippets and explanations for different PHP functionalities.

Uploaded by

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

PHP Programming Examples and Patterns

The document contains various PHP programming exercises demonstrating the use of conditional statements, loops, arrays, string functions, and object-oriented concepts. It includes examples of creating and manipulating indexed and associative arrays, implementing inheritance, and building a simple registration form. Each section provides code snippets and explanations for different PHP functionalities.

Uploaded by

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

1. Write a simple PHP program using Conditional and Logical operators.

Ans

<?php
// Sample data
$age = 20;
$isCitizen = true;

// Using conditional and logical operators


if ($age >= 18 && $isCitizen) {
echo "You are eligible to vote.";
} elseif ($age >= 18 && !$isCitizen) {
echo "You are old enough but not a citizen.";
} else {
echo "You are not eligible to vote.";
}
?>
2. Write a PHP program to demonstrate the use of If-else statement.
Ans
<?php
// Define a variable to store the age
$age = 25;

if ($age >= 18) {


echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
?>
3. Write Calendar program in PHP using Switch statement.

<?php
// Define a function to display the calendar
function displayCalendar($month, $year) {
// Define the number of days in each month
switch ($month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
$days = 31;
break;
case 4:
case 6:
case 9:
case 11:
$days = 30;
break;
case 2:
// Check for leap year
if (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0) {
$days = 29;
} else {
$days = 28;
}
break;
default:
echo "Invalid month.";
return;
}

// Display the calendar


echo "Calendar for $month/$year:\n";
for ($i = 1; $i <= $days; $i++) {
echo "$i ";
if ($i % 7 == 0) {
echo "\n";
}
}
}

// Test the function


$month = 5; // February
$year = 2024;
displayCalendar($month, $year);
?>
4. Write a PHP program to print first 30 even numbers. (Using for, while,
do..while)
Using For Loop

<?php
echo "First 30 even numbers (For Loop):\n";
for ($i = 2; $i <= 60; $i += 2) {
echo "$i ";
}
?>
Using While Loop

<?php
echo "First 30 even numbers (While Loop):\n";
$i = 2;
while ($i <= 60) {
echo "$i ";
$i += 2;
}
?>

Using Do..While Loop

<?php
echo "First 30 even numbers (Do..While Loop):\n";
$i = 2;
do {
echo "$i ";
$i += 2;
} while ($i <= 60);
?>

5. Write a PHP program to print the following pattern.

<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
// Print leading spaces
for ($j = 1; $j <= $rows - $i; $j++) {
echo " ";
}

// Print stars with spaces between them


for ($k = 1; $k <= $i; $k++) {
echo "* ";
}

echo "\n";
}

?>
6. Write a PHP program to print the following pattern.

<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
// Print leading spaces
for ($j = 1; $j <= $rows - $i; $j++) {
echo " ";
}

// Print stars
for ($k = 1; $k <= $i; $k++) {
echo "* ";
}

echo "\n";
}

?>

7. Write a PHP program to print the following pattern.


<?php
$row=1;
$col=1;
$num=1;
for($row=1;$row<=5;$row++)
{
for($col=1;$col<=$row;$col++)
{
echo " $num";
}
$num++;
echo"\n";
}

?>
8. Write a PHP program to print the following pattern.

<?php
$row=1;
$col=1;
$num=1;
for($row=1;$row<=5;$row++){
for($col=1;$col<=$row;$col++){
echo $num."\t";
$num++;
}
echo"</br>";
}

?>
9. Write a PHP program to demonstrate the use of Looping structures using-
a) While statement
b) Foreach statement

a) While Statement

<?php
// Initialize a variable
$i = 1;

// Use while loop to print numbers from 1 to 5


echo "Numbers from 1 to 5:\n";
while ($i <= 5) {
echo "$i ";
$i++;
}
?>

b) Foreach Statement

<?php
// Define an array
$colors = array("Red", "Green", "Blue", "Yellow", "Orange");

// Use foreach loop to print array elements


echo "Colors:\n";
foreach ($colors as $color) {
echo "$color ";
}
?>
10. Write a PHP program for creating and manipulating-
a) Indexed array b) Associative array

a) Indexed Array

<?php
// Create an indexed array
$fruits = array("Apple", "Banana", "Cherry", "Date");

// Print the array


echo "Fruits:\n";
print_r($fruits);

// Access and modify an element


$fruits[1] = "Mango";
echo "\nUpdated Fruits:\n";
print_r($fruits);

// Add a new element


$fruits[] = "Orange";
echo "\nFruits after adding a new element:\n";
print_r($fruits);
?>

b) Associative Array

<?php
// Create an associative array
$person = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York"
);

// Print the array


echo "Person:\n";
print_r($person);

// Access and modify an element


$person["age"] = 31;
echo "\nUpdated Person:\n";
print_r($person);

// Add a new element


$person["country"] = "USA";
echo "\nPerson after adding a new element:\n";
print_r($person);
?>

11. Write a PHP program for creating and manipulating-


a) Indexed array b) Multidimensional array

a) Indexed Array
<?php
// Create an indexed array
$fruits = array("Apple", "Banana", "Cherry", "Date");

// Print the array


echo "Fruits:\n";
print_r($fruits);

// Access and modify an element


$fruits[1] = "Mango";
echo "\nUpdated Fruits:\n";
print_r($fruits);

// Add a new element


$fruits[] = "Orange";
echo "\nFruits after adding a new element:\n";
print_r($fruits);

// Remove an element
unset($fruits[2]);
echo "\nFruits after removing an element:\n";
print_r($fruits);
?>

b) Multidimensional Array

<?php
// Create a multidimensional array
$students = array(
array("John", 20, "Math"),
array("Alice", 22, "Science"),
array("Bob", 21, "History")
);

// Print the array


echo "Students:\n";
print_r($students);

// Access and modify an element


$students[1][1] = 23;
echo "\nUpdated Students:\n";
print_r($students);

// Add a new element


$students[] = array("Charlie", 20, "English");
echo "\nStudents after adding a new element:\n";
print_r($students);

// Access a specific element


echo "\nStudent Name: " . $students[0][0];
?>
12. Write a PHP program to-
• Calculate length of string.
• Count the number of words in string without using string functions.
<?php
function calculateLength($str) {
$length = 0;
for ($i = 0; isset($str[$i]); $i++) {
$length++;
}
return $length;
}

function countWords($str) {
$wordCount = 0;
$inWord = false;
$i = 0;
while (isset($str[$i])) {
if ($str[$i] == " " && $inWord) {
$inWord = false;
} elseif ($str[$i] != " " && !$inWord) {
$wordCount++;
$inWord = true;
}
$i++;
}
return $wordCount;
}

$str = "Hello World this is a test";

echo "String: $str\n";


echo "Length of string: " . calculateLength($str) . "\n";
echo "Number of words: " . countWords($str);
?>

13. Write a simple PHP program to demonstrate the use of various built-in string
functions.
<?php
$str = "hello world";

// str_word_count()
echo "Number of words: " . str_word_count($str) . "\n";

// strlen()
echo "Length of string: " . strlen($str) . "\n";
// strrev()
echo "Reversed string: " . strrev($str) . "\n";

// str_replace()
echo "String after replacing 'world' with 'php': " . str_replace("world", "php", $str) .
"\n";

// ucwords()
echo "String with first letter of each word capitalized: " . ucwords($str) . "\n";

// strcmp()
$str1 = "hello";
$str2 = "world";
echo "Comparison of '$str1' and '$str2': " . strcmp($str1, $str2) . "\n";

if (strcmp($str1, $str2) < 0) {


echo "'$str1' is less than '$str2'\n";
} elseif (strcmp($str1, $str2) > 0) {
echo "'$str1' is greater than '$str2'\n";
} else {
echo "'$str1' is equal to '$str2'\n";
}
?>
14. Write a simple PHP program to demonstrate the use of simple function and
parameterized function.
<?php
// Simple function
function greet() {
echo "Hello, World!\n";
}

// Parameterized function
function greetPerson($name) {
echo "Hello, $name!\n";
}

// Call the simple function


greet();

// Call the parameterized function


greetPerson("John");
greetPerson("Alice");
?>

15. Write a simple PHP program to demonstrate the use of various math functions.
<?php
// abs() - absolute value
echo "Absolute value of -5: " . abs(-5) . "\n";

// ceil() - ceiling
echo "Ceiling of 4.7: " . ceil(4.7) . "\n";

// floor() - floor
echo "Floor of 4.7: " . floor(4.7) . "\n";

// round() - rounding
echo "Rounded value of 4.7: " . round(4.7) . "\n";

// sqrt() - square root


echo "Square root of 16: " . sqrt(16) . "\n";

// pow() - power
echo "2 to the power of 3: " . pow(2, 3) . "\n";

// max() - maximum value


echo "Maximum value of 10, 20, 30: " . max(10, 20, 30) . "\n";

// min() - minimum value


echo "Minimum value of 10, 20, 30: " . min(10, 20, 30) . "\n";

// rand() - random number


echo "Random number between 1 and 100: " . rand(1, 100) . "\n";
?>

16. Write a simple PHP program to demonstrate the use of Anonymous function.

<?php
$add=create_function('$a,$b','return($a+$b);');
$m=$add(10,20);
echo "Addition of Two Number is $m";
?>
OR
 // Define and use an anonymous function
$sum = function($a, $b) {
return $a + $b;
};
// Output: 5
echo $sum(2, 3);

17. Write a PHP program to Calculate length of string.


<?php
$str = "Hello World";
$length = strlen($str);
echo "The length of the string '$str' is: $length";
?>

18. Write a simple PHP program to create PDF document using graphics concepts.
19. Write a PHP program to
a) Inherit members of super class in subclass.
b) Create constructor to initialize object of class by using object oriented concepts.

<?php
// Superclass
class Animal {
public $name;

function __construct($name) {
$this->name = $name;
}

function eat() {
echo "$this->name is eating.\n";
}
}

// Subclass
class Dog extends Animal {
function __construct($name) {
parent::__construct($name);
}

function bark() {
echo "$this->name is barking.\n";
}
}

// Create an object of the subclass


$dog = new Dog("Buddy");
$dog->eat();
$dog->bark();
?>
20. Write a PHP program to implement Multiple Inheritance.
<?php
trait Animal {
function eat() {
echo "Eating...\n";
}
}

trait Mammal {
function walk() {
echo "Walking...\n";
}
}

class Dog {
use Animal, Mammal;

function bark() {
echo "Barking...\n";
}
}

$dog = new Dog();


$dog->eat();
$dog->walk();
$dog->bark();
?>
21. Write a PHP program to implement Multilevel Inheritance.
<?php
// Grandparent class
class Animal {
function eat() {
echo "Eating...\n";
}
}

// Parent class
class Mammal extends Animal {
function walk() {
echo "Walking...\n";
}
}

// Child class
class Dog extends Mammal {
function bark() {
echo "Barking...\n";
}
}

$dog = new Dog();


$dog->eat();
$dog->walk();
$dog->bark();
?>

22. Write a program to design a registration form using textbox, radio button,
checkbox and button.
<?php
if (isset($_GET["name"]) && isset($_GET["email"]) && isset($_GET["gender"])
&& isset($_GET["hobbies"])) {
$name = $_GET["name"];
$email = $_GET["email"];
$gender = $_GET["gender"];
$hobbies = $_GET["hobbies"];

echo "Name: $name\n";


echo "Email: $email\n";
echo "Gender: $gender\n";
echo "Hobbies: ";
print_r($hobbies);
}
?>

<form method="get">
Name:
<input type="text" id="name" name="name"><br><br>
Email:
<input type="email" id="email" name="email"><br><br>
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="Male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br><br>
<label for="hobbies">Hobbies:</label>
<input type="checkbox" id="reading" name="hobbies[]" value="Reading">
<label for="reading">Reading</label>
<input type="checkbox" id="writing" name="hobbies[]" value="Writing">
<label for="writing">Writing</label>
<input type="checkbox" id="coding" name="hobbies[]" value="Coding">
<label for="coding">Coding</label><br><br>
<input type="submit" value="Register">
</form>

23. Develop web page with data validation.


Here is a simple PHP program that uses $_GET and validates the name and email
fields:
<?php
if (isset($_GET["name"]) && isset($_GET["email"])) {
$name = $_GET["name"];
$email = $_GET["email"];

if (empty($name)) {
echo "Name is required";
} elseif (empty($email)) {
echo "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
echo "Name: $name\n";
echo "Email: $email\n";
}
}
?>

<form method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
24. Write a PHP program to implement Introspection concept.

<?php
// Base class
class Animal {
public $name;
private $age;

public function __construct($name, $age) {


$this->name = $name;
$this->age = $age;
}

public function speak() {


echo "The animal speaks!";
}
}

// Derived class
class Dog extends Animal {
public $breed;

public function __construct($name, $age, $breed) {


parent::__construct($name, $age);
$this->breed = $breed;
}

public function speak() {


echo "The dog barks!";
}
}

// Checking if a class exists


if (class_exists("Dog")) {
echo "Dog class exists.\n";
}

// Getting the parent class of Dog


echo "Parent class of Dog: " . get_parent_class("Dog") . "\n";

// Getting methods of the Dog class


echo "Methods of Dog: " . implode(", ", get_class_methods("Dog")) . "\n";

// Getting class variables of Dog


echo "Class variables of Dog: " . implode(", ", array_keys(get_class_vars("Dog"))) .
"\n";
?>
25. Write a program to create, modify and delete a cookie.
<?php
// Create a cookie
setcookie("username", "j
ohn_doe", time() + 3600);

// Modify a cookie
setcookie("username", "jane_doe", time() + 3600);

// Access a cookie
if (isset($_COOKIE["username"])) {
echo "Username: " . $_COOKIE["username"] . "\n";
} else {
echo "Cookie not set or expired.\n";
}

// Delete a cookie
setcookie("username", "", time() - 3600);
?>
26. Write a program to start and destroy a session.
<?php
// Start a session
session_start();
$_SESSION["username"] = "john_doe";

// Access session data


if (isset($_SESSION["username"])) {
echo "Username: " . $_SESSION["username"] . "\n";
} else {
echo "Session not started or expired.\n";
}

// Destroy a session
session_unset();
session_destroy();
?>

27. Write a program to send and receive mails using PHP.


<?php
$to = "recipient@[Link]";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@[Link]";

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


echo "Email sent successfully.\n";
} else {
echo "Error sending email.\n";
}
?>
28. Write a PHP code to insert data into employee table and print it in table
format.

<?php
// Create a connection
$conn = mysqli_connect("localhost", "vjtech", "vjtech2013", "revisionphpdb");

// Check connection
if ($conn) {
echo "Connection established successfully!!!<br>";

// Create table query


$createTableQuery = "CREATE TABLE IF NOT EXISTS employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(255),
emp_salary DECIMAL(10, 2)
)";

if (mysqli_query($conn, $createTableQuery)) {
echo "Table created successfully!!!<br>";
} else {
echo "Error creating table: " . mysqli_error($conn) . "<br>";
}

// Insert data query


$insertQuery = "INSERT INTO employee VALUES ('1', 'John Doe', '50000.00')";
if (mysqli_query($conn, $insertQuery)) {
echo "Records created successfully!!!<br>";
} else {
echo "Records not created!!!<br>";
}

// Select data query


$selectQuery = "SELECT * FROM employee";
$result = mysqli_query($conn, $selectQuery);

// Print data in table format


if (mysqli_num_rows($result) > 0) {
echo "<table border='1'>
<tr>
<th>Emp ID</th>
<th>Emp Name</th>
<th>Emp Salary</th>
</tr>";

while ($row = mysqli_fetch_assoc($result)) {


echo "<tr>
<td>" . $row["emp_id"] . "</td>
<td>" . $row["emp_name"] . "</td>
<td>" . $row["emp_salary"] . "</td>
</tr>";
}

echo "</table>";
} else {
echo "No records found!!!<br>";
}
} else {
echo "Unable to connect";
}
// Close connection
mysqli_close($conn);
?>

29. Develop a simple application to Update, Delete table data from database.

<?php
// Create a connection
$conn = mysqli_connect("localhost", "vjtech", "vjtech2013", "revisionphpdb");

// Check connection
if ($conn) {
echo "Connection established successfully!!!<br>";

// Create table query


$createTableQuery = "CREATE TABLE IF NOT EXISTS employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(255),
emp_salary DECIMAL(10, 2)
)";

if (mysqli_query($conn, $createTableQuery)) {
echo "Table created successfully!!!<br>";
} else {
echo "Error creating table: " . mysqli_error($conn) . "<br>";
}

// Insert
if (isset($_POST['add'])) {
$id = $_POST['emp_id'];
$name = $_POST['emp_name'];
$salary = $_POST['emp_salary'];
$insert = "INSERT INTO employee VALUES ('$id', '$name', '$salary')";
if (mysqli_query($conn, $insert)) {
echo "Record inserted successfully!!!<br>";
} else {
echo "Insert failed!!!<br>";
}
}

// Update
if (isset($_POST['update'])) {
$id = $_POST['emp_id'];
$name = $_POST['emp_name'];
$salary = $_POST['emp_salary'];
$update = "UPDATE employee SET emp_name='$name', emp_salary='$salary'
WHERE emp_id='$id'";
if (mysqli_query($conn, $update)) {
echo "Record updated successfully!!!<br>";
} else {
echo "Update failed!!!<br>";
}
}

// Delete
if (isset($_POST['delete'])) {
$id = $_POST['emp_id'];
$delete = "DELETE FROM employee WHERE emp_id='$id'";
if (mysqli_query($conn, $delete)) {
echo "Record deleted successfully!!!<br>";
} else {
echo "Delete failed!!!<br>";
}
}

} else {
echo "Unable to connect";
}
?>

<h3>Employee Form</h3>
<form method="post">
Emp ID: <input type="text" name="emp_id" required><br>
Name: <input type="text" name="emp_name"><br>
Salary: <input type="number" step="0.01" name="emp_salary"><br><br>
<input type="submit" name="add" value="Add">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
</form>

<hr>

<h3>All Employee Records</h3>


<?php
// Fetch and show data in simple form
if ($conn) {
$select = "SELECT * FROM employee";
$result = mysqli_query($conn, $select);

if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "---------------------------<br>";
echo "Emp ID: " . $row['emp_id'] . "<br>";
echo "Name: " . $row['emp_name'] . "<br>";
echo "Salary: ₹" . $row['emp_salary'] . "<br>";
}
} else {
echo "No records found!!!<br>";
}

mysqli_close($conn);
}
?>

You might also like