Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

PHP_Examples

Uploaded by

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

PHP_Examples

Uploaded by

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

PHP EXAMPLES

Write a program to print “Hello World” using echo.


Description: Write a program to print “Hello World” using echo only?

Conditions:

• You can not use any variable.

Solution /Program

<?php
echo "Hello World";
?>

Write a program to print “Hello PHP” using variable.


Description: Write a program to print “Hello PHP” using php variable?

Conditions:

• You can not use text directly in echo but can use variable.

Solution/Program

<?php
$message = "Hello PHP";
echo $message;
?>

Write a program to print a string using echo+variable.


Description: Write a program to print “Welcome to the PHP World” using some part of the text in variable & some
part directly in echo.

Conditions:

• You have to use a variable that contains string “PHP World”.

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:

• First variable have text “Good Morning.”

• Second variable have text “Have a nice day!”

• Your output should be “Good morning. Have a nice day!”

• 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;
?>

Write a program to check student grade based on marks.


Description: Write a program to check student grade based on the marks using if-else statement.
Conditions:
• If marks are 60% or more, grade will be First Division.
• If marks between 45% to 59%, grade will be Second Division.
• If marks between 33% to 44%, grade will be Third Division.
• If marks are less than 33%, student will be Fail.
Solution/Program

<?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:

• You can pass 1 to 7 number in switch

• Day 1 will be considered as Monday

• If number is not between 1 to 7, show invalid number in default

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.

Rules & Hint

• You can use “for” or “while” loop

• You can use variable to initialize count

• You can use html tag for line break

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

<table width="400px" cellspacing="0px" cellpadding="0px" border="1px">


<?php
for($row=1;$row<=8;$row++)
{
echo "<tr>";
for($column=1;$column<=8;$column++)
{
$total=$row+$column;
if($total%2==0)
{
echo "<td height=35px width=30px bgcolor=#FFFFFF></td>";
}
else
{
echo "<td height=35px width=30px bgcolor=#000000></td>";
}
}
echo "</tr>";
}
?>
</table>

Write a Program to create given pattern with * using for loop.


Description: Write a Program to create following pattern using for loops:

**

***

****

*****

******

*******

********

Rules

• You can use for or while loop

• You can use multiple (nested) loop to draw above pattern

5
Solution/Program using two for loops

<?php
for($row=1;$row<=8;$row++)
{
for ($star=1;$star<=$row;$star++)
{
echo "*";
}
echo "<br>";
}
?>
*
**
***
****
*****
******
*******
********

Follow Simple Tips for PHP Beginners to avoid errors in Programming.

• Start with simple & small programs.

• 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.

Here is a working PHP Code example to output a simple line.

<?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

• Remove double quote from “Hello World!” what error occurs

• Remove PHP ending statement “?>” error occurs

• Use “

• Try some space between “

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

Using phpinfo() – Display PHP Configuration & Modules.


phpinfo() is a PHP built-in function used to display information about PHP’s configuration settings and modules.

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.

Example Using phpinfo() function

<?php
phpinfo();
?>

7
Output Window

Write a PHP program to add two numbers.

Description: Write a program to perform sum or addition of two numbers in PHP programming. You can use
PHP Variables and Operators

PHP Program to add two numbers:

<?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:

• 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

• You can use conditional statements.

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;

if($units <= 50) {


$bill = $units * $unit_cost_first;
}
else if($units > 50 && $units <= 100) {
$temp = 50 * $unit_cost_first;
$remaining_units = $units - 50;
$bill = $temp + ($remaining_units * $unit_cost_second);
}
else if($units > 100 && $units <= 200) {
$temp = (50 * 3.5) + (100 * $unit_cost_second);
$remaining_units = $units - 150;
$bill = $temp + ($remaining_units * $unit_cost_third);
}
else {

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>

<form action="" method="post" id="quiz-form">


<input type="number" name="units" id="units" placeholder="Please
enter no. of Units" />
<input type="submit" name="unit-submit" id="unit-submit"
value="Submit" />
</form>

<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>

Remove specific element by value from an array in PHP?.


Description: You need to write a program in PHP to remove specific element by value from an array using PHP
program.

Instructions:

• Take an array with list of month names.

• Take a variable with the name of value to be deleted.

• You can use PHP array functions or foreach loop.

Solution 1: Using array_search()

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

$months = array('jan', 'feb', 'march', 'april', 'may');


if (($key = array_search($delete_item, $months)) !== false) {
unset($months[$key]);
}

// print array to see latest values

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]);
}

// print array to see latest values

var_dump($months);
?>

Output Window

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=>
string(3) “may” }

Solution 3: Using array_diff()

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));

// print array to see latest values

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

• Minimum age required for vote is 18.

• You can use PHP Functions.

• You can use Decision Making Statements.

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

You Are Eligible For Vote

Write a PHP program to calculate area of rectangle.


Description: Write a PHP program to calculate area of rectangle by using PHP Function.

Condition

• You must use a PHP Function.

• There should be two arguments i.e. length & width.

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

Area Of Rectangle with length 2 & width 4 is 8 .

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:

• You can use if else conditions.

• You should use appropriate PHP Operators.

• Also check if it not a numeric value.

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

324 is a positive number

Write a PHP program to reverse the string.


Description: Write a PHP program to reverse the string.

Instructions:

• You can use any string related built-in Function.

• You can use only one variable.

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:

• You have to use one variable.

• You must use a built-in PHP String Function.

Solution/Program:

<?php
$str = "Tutorials Class";
echo strlen($str);
?>

Output
15

Write a PHP program to count the words in the string.


Description: Write a PHP program to count the words in the string.

Instructions:

• You can use only one variable.

• You can use PHP built-in String Function.

View Solution/Program

<?php
$sample_words = "This is Tutorials Class, learn programming tutorials here.";
echo str_word_count($sample_words);
?>

Output
8

Write a PHP program to convert a string into uppercase.


Description:
Write a PHP program to convert all the characters inside the string into uppercase.

Instructions:

• You can use only one variable.

• You should use a PHP built-in string Function

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.

• Create a form that accept name as well as colors

• After submission, form data will be sent to another page

• Display select colors (as a list) and user name

• User name & colors selection is mandatory

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.

• Let us suppose that there are two arrays.

• First array is large which have 6 values.

• Second array is small which have 2 values

• Find if second array is subset of first which means that all values of second array should exists in first array.

• You can use Decision Making Statements.

PHP Program to find if an array is a subset of another:

<?php
// Define two array
$array1 = array('a','1','2','3','4');
$array2 = array('a','3');

// intersect/matched values should be equal to first array


if (array_intersect($array2, $array1) === $array2) {
echo "It is a subset";
} else {
echo "Not a subset";
}
?>

Output

It is a subset

18

You might also like