PHP_Examples
PHP_Examples
Conditions:
Solution /Program
<?php
echo "Hello World";
?>
Conditions:
• You can not use text directly in echo but can use variable.
Solution/Program
<?php
$message = "Hello PHP";
echo $message;
?>
Conditions:
Solution/Program
<?php
$message = "Welcome to the PHP World";
echo "hello ". $message;
?>
1
Write a program to print two variables in single echo.
Description: Write a program to print 2 php variables using single echo statement.
Conditions:
• You are allowed to use only one echo statement in this program.
Solution/Program
<?php
$message_1 = "Good Morning.";
$message_2 = "Have a nice day!";
echo $message_1." ". $message_2;
?>
<?php
$marks = 40;
if ($marks>=60)
{
$grade = "First Division";
}
else if($marks>=45)
{
$grade = "Second Division";
}
else if($marks>=33)
{
$grade = "Third Division";
}
else
{
$grade = "Fail";
}
echo "Student grade: $grade";
?>
2
Write a program to show day of the week using switch.
Description: Write a program to show day of the week (for example: Monday) based on numbers using switch/case
statements.
Conditions:
Solution/Program
<?php
$day = "5";
switch ($day) {
case "1":
echo "It is Monday!";
break;
case "2":
echo "It is today!";
break;
case "3":
echo "It is Wednesday!";
break;
case "4":
echo "It is Thursday!";
break;
case "5":
echo "It is Friday!";
break;
case "6":
echo "It is Saturday!";
break;
case "7":
echo "It is Sunday!";
break;
default:
echo "Invalid number!";
}
?>
3
Write a program to count 5 to 15 using PHP loop.
Description: Write a Program to display count, from 5 to 15 using PHP loop as given below.
Solution/Program
<?php
$count = 5;
while($count <= 15)
{
echo $count;
echo "<br>" ;
$count++;
}
?>
Output
5
6
7
8
9
10
11
12
13
14
15
4
Write a program to create Chess board in PHP using for loop.
Description: Write a PHP program using nested for loop that creates a chess board.
Conditions: You can use html table having width=”400px” and take “30px” as cell height and width for check boxes.
Solution/Program
**
***
****
*****
******
*******
********
Rules
5
Solution/Program using two for loops
<?php
for($row=1;$row<=8;$row++)
{
for ($star=1;$star<=$row;$star++)
{
echo "*";
}
echo "<br>";
}
?>
*
**
***
****
*****
******
*******
********
• Type your PHP program code manually. Do not just Copy Paste.
• Always create a new file for new code and keep backup of old files. This will make it easy to find
old programs when needed.
• Keep your PHP files in organized folders rather than keeping all files in same folder.
• Use meaningful names for PHP files or folders. Some examples are: “variable-test.php“,
“loops.php” etc. Do not just use “abc.php“, “123.php” or “sample.php“
• Avoid space between file or folder names. Use hyphens (-) instead.
• Use lower case letters for file or folder names. This will help you make a consistent code
6
Experiment with Basic PHP Syntax Errors.
When you start PHP Programming, you may face some programming errors. These errors stops your program
execution. Sometimes you quickly find your solutions while sometimes it may take long time even if there is small
mistake. It is important to get familiar with Basic PHP Syntax Errors
Basic Syntax errors occurs when we do not write PHP Code correctly. We cannot avoid all those errors but we can
learn from them.
<?php
echo "Hello World!";
?>
Output
Hello World!
It is better to experiment with PHP Basic code and see what errors happens.
• Remove semicolon from the end of second line and see what error occurs
• Use “
Try above changes one at a time and see error. Observe What you did and what error happens.
Take care of the line number mentioned in error message. It will give you hint about the place where there is some
mistake in the code.
Read Carefully Error message. Once you will understand the meaning of these basic error messages, you will be able
to fix them later on easily.
Note: Most of the time error can be found in previous line instead of actual mentioned line. For example: If your
program miss semicolon in line number 6, it will show error in line number
When we install PHP, there are many additional modules also get installed. Most of them are enabled and some are
disabled. These modules or extensions enhance PHP functionality. For example, the date-time extension provides
some ready-made function related to date and time formatting. MySQL modules are integrated to deal with PHP
Connections.
It is good to take a look on those extensions. Simply use phpinfo() function as given below.
<?php
phpinfo();
?>
7
Output Window
Description: Write a program to perform sum or addition of two numbers in PHP programming. You can use
PHP Variables and Operators
<?php
$first = 15;
$second = 10;
$sum = $first + $second;
echo "Result: ".$sum;
?>
Output
Result: 25
8
Write a program to calculate Electricity bill in PHP.
Description: You need to write a PHP program to calculate electricity bill using if-else conditions.
Conditions:
Solution/Program
<!DOCTYPE html>
<head>
<title>PHP - Calculate Electricity Bill</title>
</head>
<?php
$result_str = $result = '';
if (isset($_POST['unit-submit'])) {
$units = $_POST['units'];
if (!empty($units)) {
$result = calculate_bill($units);
$result_str = 'Total amount of ' . $units . ' - ' . $result;
}
}
/**
* To calculate electricity bill as per unit cost
*/
function calculate_bill($units) {
$unit_cost_first = 3.50;
$unit_cost_second = 4.00;
$unit_cost_third = 5.20;
$unit_cost_fourth = 6.50;
9
$temp = (50 * 3.5) + (100 * $unit_cost_second) + (100 * $unit_cost_third);
$remaining_units = $units - 250;
$bill = $temp + ($remaining_units * $unit_cost_fourth);
}
return number_format((float)$bill, 2, '.', '');
}
?>
<body>
<div id="page-wrap">
<h1>Php - Calculate Electricity Bill</h1>
<div>
<?php echo '<br />' . $result_str; ?>
</div>
</div>
</body>
</html>
Output Window
10
Write a simple calculator program in PHP using switch case.
Description: You need to write a simple calculator program in PHP using switch case.
Operations:
• Addition
• Subtraction
• Multiplication
• Division
Solution/Program
<!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>
11
</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>
Instructions:
With the help of array_search() function, we can remove specific elements from an array.
<?php
$delete_item = 'march';
// take a list of months in an array
var_dump($months);
?>
12
Output
array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=>
string(3) “may” }
Solution 2: Using foreach()
By using foreach() loop, we can also remove specific elements from an array.
<?php
$delete_item = 'april';
// take a list of months in an array
$months = array('jan', 'feb', 'march', 'april', 'may'); // for april, the key is 4
foreach (array_keys($months, $delete_item) as $key) {
unset($months[$key]);
}
var_dump($months);
?>
Output Window
array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=>
string(3) “may” }
With the help of array_diff() function, we also can remove specific elements from an array.
<?php
$delete_item = 'april';
// take a list of months in an array
$months= array('jan', 'feb', 'march', 'april', 'may');
$final_months= array_diff($months, array($delete_item));
var_dump($final_months);
?>
Output Window
array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [2]=> string(5) “march” [4]=>
string(3) “may” }
13
Write a PHP program to check if a person is eligible to vote.
Description: Write a PHP program to check if a person is eligible to vote or not.
Condition
Solution/Program.
<?php
function check_vote() //function has been declared
{
$name = "Rakesh";
$age = 19;
if ($age >= 18) {
echo $name . ", you Are Eligible For Vote";
} else {
echo $name . ", you are not eligible for vote. ";
}
}
check_vote(); //function has been called
?>
Output
Condition
View Solution/Program.
<?php
function rect_area($length = 2, $width = 4) //function has declared
{
$area = $length * $width;
echo "Area Of Rectangle with length " . $length . " & width " . $width . " is " .
$area ;
}
rect_area(); // function has been called.
?>
Output
14
Write a PHP program to check whether a number is positive, negative or zero.
Description: Write a PHP program to check whether a number is positive, negative or zero.
Instructions:
Solution/Program
<?php
$number = 324; // enter any number of your choice here
if ($number > 0) // condition for positive numbers
{
echo $number . " is a positive number";
} else if ($number < 0) // condition for negative number
{
echo $number . " is a negative number ";
} else if ($number == 0) // condition for zero
{
echo "You have entered zero";
} else {
echo " please enter a numeric value";
}
?>
Output
Instructions:
Solution/Program:
<?php
$str = "Tutorials Class";
echo strrev($str);
?>
Output
ssalC slairotuT
15
Write a PHP program to find the length of the string.
Description: Write a PHP program to find the length of the string.
Instructions:
Solution/Program:
<?php
$str = "Tutorials Class";
echo strlen($str);
?>
Output
15
Instructions:
View Solution/Program
<?php
$sample_words = "This is Tutorials Class, learn programming tutorials here.";
echo str_word_count($sample_words);
?>
Output
8
Instructions:
View Solution/Program
<?php
$str = "Tutorials Class";
echo strtoupper($str);
?>
Output
TUTORIALS CLASS
16
PHP Array to String Conversion (favourite colours chosen by user)
Description: Write an exercise for PHP Array to String Conversion.
Solution/Program
<html>
<head>
<title>
array to string
</title>
</head>
<body>
<form action="data.php" method="post">
Username: <input type="text" name="username" placeholder="enter name"
required/><br/><br/>
Select your favourite colors:<br/>
Red<input type="checkbox" name="check_list[]" value="red"/><br/>
Blue<input type="checkbox" name="check_list[]" value="blue"/><br/>
Green<input type="checkbox" name="check_list[]" value="green"/><br/>
Yellow<input type="checkbox" name="check_list[]" value="yellow"/><br/>
Pink<input type="checkbox" name="check_list[]" value="pink"/><br/>
Black<input type="checkbox" name="check_list[]" value="black"/><br/>
White<input type="checkbox" name="check_list[]" value="white"/><br/><br/>
<input type="submit" name="submit" value="Submit"/><br/>
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
$name = $_POST['username'];
echo $name . " 's favourite colors are " . $checked_count . " option(s):
<br/>";
// Loop to store and display values of individual checked checkbox.
foreach ($_POST['check_list'] as $selected) {
echo "<p>" . $selected . "</p>";
}
} else {
echo "<b>Please Select At least One Option.</b>";
}
}
17
How to check if an array is a subset of another in PHP?
Description: You need to find whether an array is subset of another array.
• Find if second array is subset of first which means that all values of second array should exists in first array.
<?php
// Define two array
$array1 = array('a','1','2','3','4');
$array2 = array('a','3');
Output
It is a subset
18