PHP TASKS: USING FUNCTIONS
1. Compare three integers and print the largest number:
function findLargest($a, $b, $c) {
if ($a >= $b && $a >= $c) {
return $a;
} elseif ($b >= $a && $b >= $c) {
return $b;
} else {
return $c;
echo "Largest number: " . findLargest(5, 10, 15);
2. Factorial of a number:
function factorial($n) {
if ($n < 0) {
return "Invalid input";
$factorial = 1;
for ($i = 1; $i <= $n; $i++) {
$factorial *= $i;
return $factorial;
}
echo "Factorial: " . factorial(5);
3. Check if a number is prime:
function isPrime($num) {
if ($num < 2) {
return false;
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
return false;
return true;
echo isPrime(7) ? "Prime" : "Not Prime";
4. Reverse a string from user input:
function reverseString($str) {
return strrev($str);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['string'];
echo "Reversed string: " . reverseString($input);
?>
<form method="post">
<input type="text" name="string">
<button type="submit">Submit</button>
</form>
5. Check if a string is all lowercase:
function isAllLowercase($str) {
return $str === strtolower($str);
echo isAllLowercase("hello") ? "All lowercase" : "Not all lowercase";
6. Check if a string is a palindrome:
function isPalindrome($str) {
$str = strtolower(str_replace(' ', '', $str));
return $str === strrev($str);
echo isPalindrome("madam") ? "Palindrome" : "Not a Palindrome";
7. Sort an array:
function sortArray($arr) {
sort($arr);
return $arr;
print_r(sortArray([5, 3, 8, 1]));
8. Remove whitespaces from a string:
function removeWhitespaces($str) {
return str_replace(' ', '', $str);
echo removeWhitespaces("The quick brown fox");
9. Sum of the first N odd numbers:
function sumOddNumbers($n) {
$sum = 0;
$count = 0;
$num = 1;
while ($count < $n) {
$sum += $num;
$num += 2;
$count++;
return $sum;
echo "Sum of first 5 odd numbers: " . sumOddNumbers(5);
10. Login page with user validation:
function validateUser($username, $password, $users) {
return isset($users[$username]) && $users[$username] === $password;
$users = ['user1' => 'password1', 'user2' => 'password2'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
if (validateUser($username, $password, $users)) {
echo "Welcome, $username!";
} else {
echo "Error: Invalid username or password.";
?>
<form method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
11. Check if an email is valid:
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
echo isValidEmail("test@example.com") ? "Valid email" : "Invalid email";