Sharing is caring!

php exercises and solutions pdf
Contents hide
8 Additional Exercises

Introduction to PHP Exercises and Solutions

Are you learning PHP or looking for practical exercises to sharpen your skills? This blog provides 100 PHP Exercises and Solutions covering a variety of topics from basic syntax to advanced concepts. Each exercise comes with a solution to help you understand how it’s done.

php exercises and solutions pdf
php exercises
php loop exercises
chatbot em php
how to create php project
how to make php project step by step
100 proyectos en visual basic gratis código fuente

Basics of PHP

1. Hello, World!

Exercise: Write a PHP script to display “Hello, World!”. Solution:

<?php
  echo "Hello, World!";
?>

2. PHP Variables

Exercise: Create three variables ($x, $y, $z), assign values to them, and display their sum. Solution:

<?php
  $x = 10;
  $y = 20;
  $z = 30;
  echo $x + $y + $z;
?>

3. String Concatenation

Exercise: Combine two strings “Hello” and “World” into one and display it. Solution:

<?php
  $str1 = "Hello";
  $str2 = "World";
  echo $str1 . " " . $str2;
?>

4. Arithmetic Operations

Exercise: Perform addition, subtraction, multiplication, and division with two numbers. Solution:

<?php
  $a = 15;
  $b = 3;
  echo "Addition: " . ($a + $b) . "\n";
  echo "Subtraction: " . ($a - $b) . "\n";
  echo "Multiplication: " . ($a * $b) . "\n";
  echo "Division: " . ($a / $b);
?>

Conditional Statements

5. Check Even or Odd

Exercise: Write a PHP script to check if a number is even or odd. Solution:

<?php
  $number = 7;
  if ($number % 2 == 0) {
      echo "$number is Even";
  } else {
      echo "$number is Odd";
  }
?>

6. Maximum of Three Numbers

Exercise: Write a PHP script to find the largest of three numbers. Solution:

<?php
  $x = 10;
  $y = 20;
  $z = 15;
  echo max($x, $y, $z);
?>

7. Leap Year Checker

Exercise: Write a PHP script to check if a year is a leap year. Solution:

<?php
  $year = 2024;
  if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
      echo "$year is a leap year";
  } else {
      echo "$year is not a leap year";
  }
?>

Loops in PHP

8. Print Numbers 1 to 10

Exercise: Use a loop to display numbers from 1 to 10. Solution:

<?php
  for ($i = 1; $i <= 10; $i++) {
      echo $i . " ";
  }
?>

9. Sum of First 100 Numbers

Exercise: Write a script to calculate the sum of numbers from 1 to 100. Solution:

<?php
  $sum = 0;
  for ($i = 1; $i <= 100; $i++) {
      $sum += $i;
  }
  echo $sum;
?>

10. Multiplication Table

Exercise: Display the multiplication table of 5. Solution:

<?php
  $number = 5;
  for ($i = 1; $i <= 10; $i++) {
      echo "$number x $i = " . ($number * $i) . "\n";
  }
?>

Arrays in PHP

11. Array Traversal

Exercise: Write a PHP script to traverse and display elements of an array. Solution:

<?php
  $fruits = ["Apple", "Banana", "Cherry"];
  foreach ($fruits as $fruit) {
      echo $fruit . " ";
  }
?>

12. Find Maximum in an Array

Exercise: Write a PHP script to find the largest number in an array. Solution:

<?php
  $numbers = [10, 25, 35, 50, 5];
  echo max($numbers);
?>

Functions in PHP

13. Create a Simple Function

Exercise: Create a function that takes two numbers and returns their sum. Solution:

<?php
  function add($a, $b) {
      return $a + $b;
  }
  echo add(5, 10);
?>

14. Palindrome Checker

Exercise: Write a function to check if a string is a palindrome. Solution:

<?php
  function isPalindrome($string) {
      $reversed = strrev($string);
      return $string === $reversed;
  }
  echo isPalindrome("madam") ? "Palindrome" : "Not a Palindrome";
?>

Advanced Topics

15. Database Connection

Exercise: Write a PHP script to connect to a MySQL database. Solution:

<?php
  $host = "localhost";
  $user = "root";
  $password = "";
  $dbname = "test";
  $conn = new mysqli($host, $user, $password, $dbname);
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }
  echo "Connected successfully";
?>

Additional Exercises

16 to 100:

For brevity, the following exercises cover more complex topics like file handling, error handling, sessions, cookies, OOP in PHP, and security. Each includes its solution.


16. Reading from a File

Exercise: Write a script to read and display the contents of a file. Solution:

<?php
  $filename = "example.txt";
  if (file_exists($filename)) {
      $content = file_get_contents($filename);
      echo $content;
  } else {
      echo "File not found.";
  }
?>

17. Writing to a File

Exercise: Write a script to write data to a file. Solution:

<?php
  $filename = "example.txt";
  $data = "Hello, file!";
  file_put_contents($filename, $data);
?>

18. Reverse a String

Exercise: Reverse a given string using PHP.
Solution:

<?php
  $string = "Hello, World!";
  echo strrev($string); // Output: !dlroW ,olleH
?>

19. Convert String to Uppercase

Exercise: Write a script to convert a string to uppercase.
Solution:

<?php
  $string = "php is awesome!";
  echo strtoupper($string); // Output: PHP IS AWESOME!
?>

20. Calculate Length of a String

Exercise: Write a PHP script to calculate the length of a string.
Solution:

<?php
  $string = "Learn PHP!";
  echo strlen($string); // Output: 10
?>

21. Simple Interest Calculation

Exercise: Write a script to calculate simple interest using the formula:
SI=Principal×Rate×Time100\text{SI} = \frac{\text{Principal} \times \text{Rate} \times \text{Time}}{100}
Solution:

<?php
  $principal = 1000;
  $rate = 5;
  $time = 2;
  $simple_interest = ($principal * $rate * $time) / 100;
  echo $simple_interest; // Output: 100
?>

22. Swap Two Numbers

Exercise: Write a script to swap two numbers without using a third variable.
Solution:

<?php
  $a = 5;
  $b = 10;

  $a = $a + $b;
  $b = $a - $b;
  $a = $a - $b;

  echo "a = $a, b = $b"; // Output: a = 10, b = 5
?>
PHP exercises and solutions
PHP exercises for beginners
PHP exercises online
PHP free projects with source code
PHP from scratch 2024
PHP if else exercise

23. Check Divisibility

Exercise: Write a script to check if a number is divisible by 5 and 7.
Solution:

<?php
  $number = 35;
  if ($number % 5 == 0 && $number % 7 == 0) {
      echo "$number is divisible by 5 and 7";
  } else {
      echo "$number is not divisible by 5 and 7";
  }
?>

24. Check Positive, Negative, or Zero

Exercise: Write a PHP script to check if a number is positive, negative, or zero.
Solution:

<?php
  $number = -10;
  if ($number > 0) {
      echo "Positive";
  } elseif ($number < 0) {
      echo "Negative";
  } else {
      echo "Zero";
  }
?>

25. Display Current Date and Time

Exercise: Write a script to display the current date and time in the format Y-m-d H:i:s.
Solution:

<?php
  echo date("Y-m-d H:i:s"); // Example Output: 2024-12-27 14:35:00
?>

26. Check if a Year is Leap Year

Exercise: Write a PHP script to check if a given year is a leap year.
Solution:

<?php
  $year = 2024;
  if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
      echo "$year is a leap year";
  } else {
      echo "$year is not a leap year";
  }
?>

27. Find the Largest of Two Numbers

Exercise: Write a PHP script to find the largest of two numbers.
Solution:

<?php
  $a = 15;
  $b = 20;
  echo ($a > $b) ? "$a is larger" : "$b is larger"; // Output: 20 is larger
?>

28. Generate a Random Number Between 1 and 10

Exercise: Write a script to generate a random number between 1 and 10.
Solution:

<?php
  echo rand(1, 10); // Example Output: 7
?>

29. Print Numbers Using a While Loop

Exercise: Write a PHP script to print numbers from 1 to 10 using a while loop.
Solution:

<?php
  $i = 1;
  while ($i <= 10) {
      echo $i . " ";
      $i++;
  }
?>

30. Check If a Number is Odd or Even

<?php
  $number = 12;
  if ($number % 2 == 0) {
      echo "$number is Even";
  } else {
      echo "$number is Odd";
  }
?>

31. Add Two Numbers from User Input

<?php
  $a = (int)readline("Enter the first number: ");
  $b = (int)readline("Enter the second number: ");
  echo "The sum is: " . ($a + $b);
?>

32. Reverse an Integer

<?php
  $number = 1234;
  echo strrev((string)$number); // Output: 4321
?>

33. Sum of Digits

<?php
  $number = 1234;
  $sum = array_sum(str_split($number));
  echo "The sum of digits is: $sum"; // Output: 10
?>

34. Find the Smallest Number in an Array

<?php
  $numbers = [12, 5, 8, 19, 3];
  echo "The smallest number is: " . min($numbers); // Output: 3
?>

35. Check If an Array is Empty

<?php
  $array = [];
  if (empty($array)) {
      echo "The array is empty";
  } else {
      echo "The array is not empty";
  }
?>

36. Check If a String is Empty

<?php
  $string = "";
  if (empty($string)) {
      echo "The string is empty";
  } else {
      echo "The string is not empty";
  }
?>

37. Calculate the Area of a Circle

<?php
  $radius = 7;
  $area = pi() * pow($radius, 2);
  echo "The area of the circle is: $area"; // Output: 153.9380400259
?>

38. Remove Vowels from a String

<?php
  $string = "Remove all vowels from this string.";
  $noVowels = preg_replace('/[aeiouAEIOU]/', '', $string);
  echo $noVowels; // Output: Rmv ll vwls frm ths strng.
?>

39. Check Palindrome String

<?php
  $string = "madam";
  $reversed = strrev($string);
  if ($string === $reversed) {
      echo "$string is a palindrome";
  } else {
      echo "$string is not a palindrome";
  }
?>

40. Check if a String is a Valid URL

function isValidUrl($url) {
    return filter_var($url, FILTER_VALIDATE_URL) !== false;
}

echo isValidUrl("https://www.example.com") ? "Valid URL" : "Invalid URL";  

41. Remove Leading and Trailing Whitespaces from a String

function trimWhitespaces($str) {
    return trim($str);
}

echo trimWhitespaces("  Hello World!  ");  // Output: Hello World!

42. Convert a String to Lowercase

function toLowerCase($str) {
    return strtolower($str);
}

echo toLowerCase("HELLO WORLD!");  // Output: hello world!

43. Find the Smallest Element in an Array

function findSmallest($arr) {
    return min($arr);
}

$array = [10, 20, 30, 5, 15];
echo findSmallest($array);  // Output: 5

44. Replace a Word in a String

function replaceWord($str, $oldWord, $newWord) {
    return str_replace($oldWord, $newWord, $str);
}

echo replaceWord("Hello World", "World", "PHP");  // Output: Hello PHP

45. Check if a String Contains a Substring

function containsSubstring($str, $substring) {
    return strpos($str, $substring) !== false;
}

echo containsSubstring("Hello World", "World") ? "Contains" : "Does not contain";  // Output: Contains

46. Calculate the Length of a String

function stringLength($str) {
    return strlen($str);
}

echo stringLength("Hello World!");  // Output: 12

47. Check if a String is a Palindrome

function isPalindrome($str) {
    $cleanedStr = strtolower(preg_replace("/[^a-zA-Z0-9]/", "", $str));
    return $cleanedStr === strrev($cleanedStr);
}

echo isPalindrome("A man, a plan, a canal, Panama") ? "Palindrome" : "Not Palindrome";  // Output: Palindrome

48. Sort an Array in Descending Order

function sortArrayDescending($arr) {
    rsort($arr);
    return $arr;
}

$array = [5, 2, 8, 1, 4];
print_r(sortArrayDescending($array));  // Output: Array ( [0] => 8 [1] => 5 [2] => 4 [3] => 2 [4] => 1 )

49. Convert a String to an Array of Words

function stringToArray($str) {
    return explode(' ', $str);
}

print_r(stringToArray("Hello World!"));  // Output: Array ( [0] => Hello [1] => World! )

50. Sum All Elements in an Array

function sumArray($arr) {
    return array_sum($arr);
}

$array = [1, 2, 3, 4, 5];
echo sumArray($array);  // Output: 15

51. Find the Intersection of Two Arrays

function arrayIntersection($arr1, $arr2) {
    return array_intersect($arr1, $arr2);
}

$array1 = [1, 2, 3, 4];
$array2 = [3, 4, 5, 6];
print_r(arrayIntersection($array1, $array2));  // Output: Array ( [2] => 3 [3] => 4 )
PHP online exercises
PHP practice exercises
PHP programming exercises
PHP source code projects

52. Convert an Array to a Comma-Separated String

function arrayToString($arr) {
    return implode(", ", $arr);
}

$array = [1, 2, 3, 4];
echo arrayToString($array);  // Output: 1, 2, 3, 4

53. Find the Factorial of a Number Using a Loop

function factorial($n) {
    $result = 1;
    for ($i = 1; $i <= $n; $i++) {
        $result *= $i;
    }
    return $result;
}

echo factorial(5);  // Output: 120

54. Check if a String Starts with a Specific Substring

function startsWith($str, $prefix) {
    return substr($str, 0, strlen($prefix)) === $prefix;
}

echo startsWith("Hello World", "Hello") ? "Starts with" : "Does not start with";  // Output: Starts with

55. Check if a String Ends with a Specific Substring

function endsWith($str, $suffix) {
    return substr($str, -strlen($suffix)) === $suffix;
}

echo endsWith("Hello World", "World") ? "Ends with" : "Does not end with";  // Output: Ends with

56. Find the Sum of Odd Numbers in an Array

function sumOddNumbers($arr) {
    return array_sum(array_filter($arr, function($num) {
        return $num % 2 !== 0;
    }));
}

$array = [1, 2, 3, 4, 5];
echo sumOddNumbers($array);  // Output: 9

57. Generate a Random Number Between Two Values

function generateRandomNumber($min, $max) {
    return rand($min, $max);
}

echo generateRandomNumber(1, 100);  // Output: Random number between 1 and 100

58. Count the Number of Words in a String

function wordCount($str) {
    return str_word_count($str);
}

echo wordCount("Hello, how are you?");  // Output: 4

59. Check if a Year is a Leap Year

function isLeapYear($year) {
    return ($year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0));
}

echo isLeapYear(2024) ? "Leap Year" : "Not Leap Year";  // Output: Leap Year

60. Create a Simple Counter with Sessions

session_start();
if (!isset($_SESSION['counter'])) {
    $_SESSION['counter'] = 1;
} else {
    $_SESSION['counter']++;
}
echo "You have visited this page " . $_SESSION['counter'] . " times.";

61. Generate a Random String of a Given Length

function generateRandomString($length = 10) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

echo generateRandomString(8);  // Output: Random string of length 8

62. Convert an Array to a JSON String

function arrayToJson($arr) {
    return json_encode($arr);
}

$array = ['name' => 'John', 'age' => 30];
echo arrayToJson($array);  // Output: {"name":"John","age":30}

63. Convert JSON String to Array

function jsonToArray($json) {
    return json_decode($json, true);
}

$json = '{"name":"John","age":30}';
print_r(jsonToArray($json));  // Output: Array ( [name] => John [age] => 30 )

64. Create an Associative Array from Two Indexed Arrays

function combineArrays($keys, $values) {
    return array_combine($keys, $values);
}

$keys = ['name', 'age'];
$values = ['John', 30];
print_r(combineArrays($keys, $values));  // Output: Array ( [name] => John [age] => 30 )

65. Find the Difference Between Two Arrays

function arrayDifference($arr1, $arr2) {
    return array_diff($arr1, $arr2);
}

$array1 = [1, 2, 3, 4];
$array2 = [3, 4, 5, 6];
print_r(arrayDifference($array1, $array2));  // Output: Array ( [0] => 1 [1] => 2 )

66. Check if a String Contains Only Digits

function isDigitsOnly($str) {
    return ctype_digit($str);
}

echo isDigitsOnly("12345") ? "Only digits" : "Contains non-digits";  // Output: Only digits

67. Remove Duplicates from an Array

function removeDuplicates($arr) {
    return array_values(array_unique($arr));
}

$array = [1, 2, 3, 4, 4, 5, 6, 1];
print_r(removeDuplicates($array));  // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

68. Find the Square of a Number

function square($num) {
    return $num * $num;
}

echo square(5);  // Output: 25

69. Sort an Associative Array by Value

function sortAssociativeArrayByValue($arr) {
    asort($arr);
    return $arr;
}

$array = ['apple' => 3, 'banana' => 1, 'cherry' => 2];
print_r(sortAssociativeArrayByValue($array));  // Output: Array ( [banana] => 1 [cherry] => 2 [apple] => 3 )

70. Sort an Associative Array by Key

function sortAssociativeArrayByKey($arr) {
    ksort($arr);
    return $arr;
}

$array = ['apple' => 3, 'banana' => 1, 'cherry' => 2];
print_r(sortAssociativeArrayByKey($array));  // Output: Array ( [apple] => 3 [banana] => 1 [cherry] => 2 )

71. Check if a Number is Even or Odd

function isEvenOrOdd($num) {
    return $num % 2 == 0 ? 'Even' : 'Odd';
}

echo isEvenOrOdd(7);  // Output: Odd

72. Merge Two Multidimensional Arrays

function mergeMultidimensionalArrays($arr1, $arr2) {
    return array_merge_recursive($arr1, $arr2);
}

$array1 = [['a' => 1], ['b' => 2]];
$array2 = [['c' => 3], ['d' => 4]];
print_r(mergeMultidimensionalArrays($array1, $array2));  

73. Check if a String is Numeric

function isNumeric($str) {
    return is_numeric($str);
}

echo isNumeric("12345") ? "Numeric" : "Not Numeric";  // Output: Numeric

74. Get the Current Timestamp

function getCurrentTimestamp() {
    return time();
}

echo getCurrentTimestamp();  // Output: Current timestamp

75. Format a Number with Commas as Thousands Separator

function formatNumber($num) {
    return number_format($num);
}

echo formatNumber(1000000);  // Output: 1,000,000

76. Find the Absolute Value of a Number

function absoluteValue($num) {
    return abs($num);
}

echo absoluteValue(-5);  // Output: 5

77. Create a Simple Countdown Timer

function countdown($seconds) {
    while ($seconds > 0) {
        echo $seconds . " seconds remaining\n";
        sleep(1);
        $seconds--;
    }
    echo "Time's up!";
}

countdown(5);  // Output: Countdown from 5 seconds

78. Check if a Number is a Perfect Square

function isPerfectSquare($num) {
    return sqrt($num) == (int)sqrt($num);
}

echo isPerfectSquare(16) ? "Perfect Square" : "Not Perfect Square";  // Output: Perfect Square
PHP exercises
PHP practical
PHP practice
Practice PHP
PHP in practice
PHP exercise
PHP assignments
PHP solution
PHP programming challenges
PHP coding challenges
PHP online practice

79. Get the Difference in Days Between Two Dates

function dateDifference($date1, $date2) {
    $datetime1 = new DateTime($date1);
    $datetime2 = new DateTime($date2);
    $interval = $datetime1->diff($datetime2);
    return $interval->days;
}

echo dateDifference("2024-12-01", "2024-12-27");  // Output: 26

80. Count the Number of Elements in an Array

function countArrayElements($arr) {
    return count($arr);
}

$array = [1, 2, 3, 4, 5];
echo countArrayElements($array);  // Output: 5

81. Find the Longest Word in a String

function longestWord($str) {
    $words = explode(' ', $str);
    $longest = '';
    foreach ($words as $word) {
        if (strlen($word) > strlen($longest)) {
            $longest = $word;
        }
    }
    return $longest;
}

echo longestWord("The quick brown fox jumps over the lazy dog");  // Output: jumps

82. Find the Sum of Even Numbers in an Array

function sumEvenNumbers($arr) {
    return array_sum(array_filter($arr, function($num) {
        return $num % 2 === 0;
    }));
}

$array = [1, 2, 3, 4, 5];
echo sumEvenNumbers($array);  // Output: 6

83. Convert a String to a Title Case

function toTitleCase($str) {
    return ucwords(strtolower($str));
}

echo toTitleCase("hello world");  // Output: Hello World

84. Generate an Array of Fibonacci Numbers

function fibonacci($n) {
    $fib = [0, 1];
    for ($i = 2; $i < $n; $i++) {
        $fib[] = $fib[$i - 1] + $fib[$i - 2];
    }
    return $fib;
}

print_r(fibonacci(10));  // Output: Array ( [0] => 0 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 5 [6] => 8 [7] => 13 [8] => 21 [9] => 34 )

85. Find the Middle Element of an Array

function middleElement($arr) {
    $middle = floor(count($arr) / 2);
    return $arr[$middle];
}

$array = [1, 2, 3, 4, 5];
echo middleElement($array);  // Output: 3

86. 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(11) ? "Prime" : "Not Prime";  // Output: Prime

87. Convert a Multi-Dimensional Array to a Flat Array

function flattenArray($arr) {
    $result = [];
    array_walk_recursive($arr, function($item) use (&$result) {
        $result[] = $item;
    });
    return $result;
}

$array = [[1, 2], [3, 4], [5, 6]];
print_r(flattenArray($array));  // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

88. Remove Vowels from a String

function removeVowels($str) {
    return preg_replace('/[aeiouAEIOU]/', '', $str);
}

echo removeVowels("Hello World!");  // Output: Hll Wrld!

89. Merge Multiple Arrays into One

function mergeArrays(...$arrays) {
    return array_merge(...$arrays);
}

$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$array3 = [7, 8, 9];
print_r(mergeArrays($array1, $array2, $array3));  // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 )

90. Check if Two Strings are Anagrams

function areAnagrams($str1, $str2) {
    return count_chars(strtolower($str1), 1) == count_chars(strtolower($str2), 1);
}

echo areAnagrams("listen", "silent") ? "Anagrams" : "Not Anagrams";  // Output: Anagrams

91. Reverse an Array

function reverseArray($arr) {
    return array_reverse($arr);
}

$array = [1, 2, 3, 4];
print_r(reverseArray($array));  // Output: Array ( [0] => 4 [1] => 3 [2] => 2 [3] => 1 )

92. Calculate the Power of a Number

function power($base, $exp) {
    return pow($base, $exp);
}

echo power(2, 3);  // Output: 8

93. Create a Simple Calculator

function calculator($num1, $num2, $operation) {
    switch ($operation) {
        case 'add':
            return $num1 + $num2;
        case 'subtract':
            return $num1 - $num2;
        case 'multiply':
            return $num1 * $num2;
        case 'divide':
            return $num2 != 0 ? $num1 / $num2 : 'Division by zero error';
        default:
            return 'Invalid operation';
    }
}

echo calculator(10, 5, 'add');  // Output: 15

94. Count the Frequency of Each Element in an Array

function countFrequency($arr) {
    return array_count_values($arr);
}

$array = [1, 2, 2, 3, 3, 3, 4];
print_r(countFrequency($array));  // Output: Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 1 )

95. Sum of Digits of a Number

function sumOfDigits($num) {
    return array_sum(str_split($num));
}

echo sumOfDigits(12345);  // Output: 15

96. Convert a String to an Integer

function stringToInt($str) {
    return (int)$str;
}

echo stringToInt("1234");  // Output: 1234

97. Find the Largest Element in an Array

function findLargest($arr) {
    return max($arr);
}

$array = [1, 2, 3, 4, 5];
echo findLargest($array);  // Output: 5

98. Get the First and Last Elements of an Array

function firstAndLast($arr) {
    return [$arr[0], $arr[count($arr) - 1]];
}

$array = [1, 2, 3, 4, 5];
print_r(firstAndLast($array));  // Output: Array ( [0] => 1 [1] => 5 )

99. Find the Common Elements Between Two Arrays

function commonElements($arr1, $arr2) {
    return array_intersect($arr1, $arr2);
}

$array1 = [1, 2, 3, 4];
$array2 = [3, 4, 5, 6];
print_r(commonElements($array1, $array2));  // Output: Array ( [2] => 3 [3] => 4 )

100. Remove All Whitespaces from a String

function removeWhitespaces($str) {
    return str_replace(' ', '', $str);
}

echo removeWhitespaces("Hello World!");  // Output: HelloWorld!

Conclusion

This list provides exercises to practice core PHP concepts, from beginner to advanced levels. Work through these examples and build your proficiency in PHP. As you improve, try creating your own exercises to tackle real-world problems!

Stay tuned for more detailed solutions and projects in future posts!

Categories: PHP

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *