PHP All Exercises & Assignments
All 31 PHP exercises in one list: variables and echo, operators, if/else and switch, loops, strings, arrays, functions and a MySQL table.
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.
Rules and hints:
- Use if else conditions.
- Use the correct PHP operators.
- Also check that the value is a number.
- Write the logic in a function, so you can test many values.
PHP program to check a positive, negative or zero number
<?php
function checkNumber($number) {
if (!is_numeric($number)) {
return "Please enter a number";
}
if ($number > 0) {
return $number . " is a positive number";
} elseif ($number < 0) {
return $number . " is a negative number";
}
return "The number is zero";
}
echo checkNumber(324) . "<br>";
echo checkNumber(-15) . "<br>";
echo checkNumber(0) . "<br>";
echo checkNumber("abc");
?>
Output:
324 is a positive number
-15 is a negative number
The number is zero
Please enter a number
How it works
is_numeric()checks that the value is a number, so text like “abc” is rejected first.- If the number is bigger than 0 it is positive, if it is smaller than 0 it is negative. The only remaining case is zero.
- Because it is a function, you can call it with different values.
Write a PHP program to reverse the string
Description: Write a PHP program to reverse a string.
Rules and hints:
- You can use any string related built-in function.
- Use only one variable.
PHP program to reverse a string
<?php
$str = "Tutorials Class";
echo strrev($str);
?>
Output:
ssalC slairotuT
How it works
strrev()reverses the order of all characters, including the space.
Try this too
- Check if a word is a palindrome (same when reversed), like “madam”.
- Reverse the order of the words, and not the letters.
Write a PHP program to find the length of the string
Description: Write a PHP program to find the length of a string.
Rules and hints:
- Use one variable.
- Use a built-in PHP string function.
PHP program to find the length of a string
<?php
$str = "Tutorials Class";
echo strlen($str);
?>
Output:
15
How it works
strlen()returns the number of characters (bytes) of the string.- The space between the two words is counted too, so the length is 15.
For non-English text read strlen() vs mb_strlen().
Write a PHP program to count the words in the string
Description: Write a PHP program to count the number of words in a string.
Rules and hints:
- Use only one variable.
- Use a PHP built-in string function.
PHP program to count the words in a string
<?php
$sample_words = "This is Tutorials Class, learn programming tutorials here.";
echo str_word_count($sample_words);
?>
Output:
8
How it works
str_word_count()counts the words made of letters. Commas and spaces are not counted as words.- The sentence has 8 words.
More about it: How to count the words of a string in PHP.
Write a PHP program to convert a string into uppercase
Description: Write a PHP program to convert all the characters of a string into uppercase.
Rules and hints:
- Use only one variable.
- Use a PHP built-in string function.
PHP program to convert a string into uppercase
<?php
$str = "Tutorials Class";
echo strtoupper($str);
?>
Output:
TUTORIALS CLASS
How it works
strtoupper()returns the string with all letters in capital.- For text in other languages (like accents) use
mb_strtoupper().
Related: PHP String Handling and ucwords().
PHP Array to String Conversion (favourite colours chosen by user)
Description: Write a PHP exercise for array to string conversion.
Rules and hints:
- Create a form that accepts a name and some colors (checkboxes).
- After the submit, the data goes to another page.
- Show the user name and the selected colors as a list.
- The name and at least one color are required.
Step 1: the form (index.html)
<form action="data.php" method="post">
Name: <input type="text" name="username" required><br><br>
Select your favourite colors:<br>
<input type="checkbox" name="colors[]" value="Red"> Red
<input type="checkbox" name="colors[]" value="Green"> Green
<input type="checkbox" name="colors[]" value="Blue"> Blue
<input type="checkbox" name="colors[]" value="Yellow"> Yellow<br><br>
<button type="submit">Send</button>
</form>
The name colors[] (with the square brackets) tells PHP to collect all the selected values in an array.
Step 2: data.php
<?php
$username = trim($_POST["username"] ?? "");
$colors = $_POST["colors"] ?? [];
if ($username === "" || empty($colors)) {
exit("Name and at least one color are required.");
}
echo "Hello " . htmlspecialchars($username) . "<br>";
echo "Your favourite colors: " . htmlspecialchars(implode(", ", $colors));
?>
Output:
Hello Robin
Your favourite colors: Red, Blue
How it works
$_POST["colors"]is an array of the checked boxes.implode(", ", $colors)converts the array to a text. See how to convert an array to a string.htmlspecialchars()protects the page from XSS.
How to check if an array is a subset of another in PHP?
Description: Write a PHP program to find out if an array is a subset of another array.
Rules and hints:
- The first array is large, and the second array is small.
- The second array is a subset if all of its values exist in the first array.
- You can use decision making statements.
PHP program to check if an array is a subset of another
<?php
$array1 = ["a", "1", "2", "3", "4"];
$array2 = ["a", "3"];
$array3 = ["a", "z"];
// array_diff gives the values of the first array that are missing in the second
if (count(array_diff($array2, $array1)) === 0) {
echo "array2 is a subset of array1<br>";
} else {
echo "array2 is not a subset of array1<br>";
}
if (count(array_diff($array3, $array1)) === 0) {
echo "array3 is a subset of array1";
} else {
echo "array3 is not a subset of array1";
}
?>
Output:
array2 is a subset of array1
array3 is not a subset of array1
How it works
array_diff($array2, $array1)returns the values of $array2 that are not in $array1.- If nothing is missing (the count is 0), all values exist, so it is a subset.
- “z” is not in $array1, so $array3 is not a subset.
Another way: the result of array_intersect($array2, $array1) must have the same count as $array2. See PHP Array Functions.
Display MySQL data in an HTML table using mysqli_fetch_array()
Description: Write a PHP program that reads all the records of the users table from the MySQL database and shows them in an HTML table. The newest user must come first.
Rules and hints:
- Use the
db-connection.phpfile and the users table from the PHP MySQL tutorial. - Use
mysqli_query()andmysqli_fetch_array(). - Sort the records by id, from the highest to the lowest.
PHP program to display MySQL data in an HTML table
<?php
require_once('db-connection.php');
$result = mysqli_query($conn, "SELECT * FROM users ORDER BY id DESC");
?>
<table border="1" cellpadding="6">
<tr>
<th>ID</th>
<th>Name</th>
<th>Mobile</th>
<th>Email</th>
</tr>
<?php while ($user = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $user["id"]; ?></td>
<td><?php echo htmlspecialchars($user["name"]); ?></td>
<td><?php echo htmlspecialchars($user["mobile"]); ?></td>
<td><?php echo htmlspecialchars($user["email"]); ?></td>
</tr>
<?php } ?>
</table>
Output:
| ID | Name | Mobile | |
|---|---|---|---|
| 3 | Pankit | 9898979797 | pankit@example.com |
| 2 | Sanjay | 9898969696 | sanjay@example.com |
| 1 | Ram | 9898989898 | ram@example.com |
How it works
ORDER BY id DESCsorts the records from the newest to the oldest.mysqli_fetch_array()returns one row in each call, and returns null when there are no more rows, so thewhileloop stops.- Every value is printed with
htmlspecialchars()to be safe from XSS.
The difference between the fetch functions is in mysqli_fetch_array() vs mysqli_fetch_object(). See also PHP : MySQL Select Data.
Write a PHP script to displays numbers between 100 and 150 divisible by 4
Description: Write a PHP script to display the numbers between 100 and 150 that are divisible by 4.
Rules and hints:
- Use a loop and an
ifcondition. - Use the modulus operator (
%). A number is divisible by 4 when$i % 4is 0.
PHP program for numbers divisible by 4
<?php
for ($i = 100; $i <= 150; $i++) {
if ($i % 4 == 0) {
echo $i . " ";
}
}
?>
Output:
100 104 108 112 116 120 124 128 132 136 140 144 148
How it works
- The loop checks every number from 100 to 150.
%gives the remainder of the division. If the remainder is 0, the number is divisible by 4, and it is printed.
A shorter way
Since 100 is divisible by 4, you can start from 100 and add 4 in every round. You do not need the if condition.
<?php
for ($i = 100; $i <= 150; $i += 4) {
echo $i . " ";
}
?>
Related: PHP Loops and division vs modulus.
Write a PHP Program to print 5 to 15 using Conditional statements
Description: Write a PHP program to print the numbers from 5 to 15 using conditional statements, without using any loop.
Rules and hints:
- You can use a function with arguments.
- You can not use a loop (
for,while,foreach). - You can use
ifconditions.
PHP program to print 5 to 15 without a loop
<?php
function printNumbers($current, $end) {
if ($current > $end) {
return; // stop
}
echo $current . "<br>";
printNumbers($current + 1, $end); // call the function again
}
printNumbers(5, 15);
?>
Output:
5
6
7
8
9
10
11
12
13
14
15
How it works
- The function prints the current number, and then calls itself with the next number.
- When the current number becomes bigger than the end number, the if condition stops the function. This is called recursion.
Read about PHP functions and see another example of recursion in factorial using recursion.
Create a PHP Form with 2 fields Name and Hobbies
Description: Create a PHP form with 2 fields: Name and Hobbies. After the submit, show the name and the selected hobbies.
Rules and hints:
- Name: a text input.
- Hobbies: checkboxes with these options: Singing, Reading, Dancing, Travelling and Drawing.
- The user can select more than one hobby.
PHP program with a form and hobbies
<?php
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$hobbies = $_POST["hobbies"] ?? [];
if ($name === "") {
$message = "Please enter your name.";
} elseif (empty($hobbies)) {
$message = "Please select at least one hobby.";
} else {
$message = "The hobbies of " . htmlspecialchars($name) . " are: " . htmlspecialchars(implode(", ", $hobbies));
}
}
?>
<form method="post">
Name: <input type="text" name="name"><br><br>
Hobbies:<br>
<input type="checkbox" name="hobbies[]" value="Singing"> Singing
<input type="checkbox" name="hobbies[]" value="Reading"> Reading
<input type="checkbox" name="hobbies[]" value="Dancing"> Dancing
<input type="checkbox" name="hobbies[]" value="Travelling"> Travelling
<input type="checkbox" name="hobbies[]" value="Drawing"> Drawing<br><br>
<button type="submit">Submit</button>
</form>
<p><?php echo $message; ?></p>
Output:
The hobbies of Robin are: Singing, Dancing
How it works
- The checkboxes have the same name
hobbies[], so PHP collects all the checked values in an array. implode()joins the array values with commas.- The form and the PHP code are in the same file, and the code runs only after the form is submitted (POST).
htmlspecialchars()keeps the output safe.
Related: PHP Forms Handling.
- « Previous
- 1
- 2