Functions in PHP

1. Function to print “Hello PHP”

				
					<?php
function greet(){
    echo "Hello PHP";
}

greet();
?>

				
			

2. Function to add two numbers

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

echo "Sum: " . add(10, 20);
?>

				
			

3. Function to find square of a number

				
					<?php
function square($num){
    return $num * $num;
}

echo "Square: " . square(5);
?>

				
			

4. Function with default parameter values

				
					<?php
function greetUser($name = "Guest"){
    echo "Welcome, $name";
}

greetUser();
echo "<br>";
greetUser("Boby");
?>

				
			

5. Function to calculate factorial

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

echo "Factorial: " . factorial(5);
?>

				
			

6. Function to return largest of two numbers

				
					<?php
function largest($a, $b){
    return ($a > $b) ? $a : $b;
}

echo "Largest: " . largest(15, 25);
?>

				
			

7. Function to check prime number

				
					<?php
function isPrime($num){
    if($num <= 1) return false;

    for($i=2; $i<$num; $i++){
        if($num % $i == 0){
            return false;
        }
    }
    return true;
}

$num = 7;
echo isPrime($num) ? "$num is Prime" : "$num is Not Prime";
?>

				
			

8. Function to reverse a string

				
					<?php
function reverseString($str){
    return strrev($str);
}

echo reverseString("PHP");
?>

				
			

9. Function to count vowels in a string

				
					<?php
function countVowels($str){
    $count = 0;
    $str = strtolower($str);

    for($i=0; $i<strlen($str); $i++){
        if(in_array($str[$i], ['a','e','i','o','u'])){
            $count++;
        }
    }
    return $count;
}

echo "Vowels: " . countVowels("Hello PHP");
?>

				
			

10. Function to check palindrome string

				
					<?php
function isPalindrome($str){
    return ($str == strrev($str));
}

$text = "madam";

echo isPalindrome($text) ? "Palindrome" : "Not Palindrome";
?>

				
			

11. Demonstrate local and global variables

				
					<?php
$x = 10;

function test(){
    global $x;
    $y = 20;

    echo "Global x: $x <br>";
    echo "Local y: $y";
}

test();
?>

				
			

12. Recursive function for factorial

				
					<?php
function factorial($n){
    if($n == 0) return 1;
    return $n * factorial($n - 1);
}

echo "Factorial: " . factorial(5);
?>

				
			

13. Recursive Fibonacci function

				
					<?php
function fibonacci($n){
    if($n == 0) return 0;
    if($n == 1) return 1;

    return fibonacci($n-1) + fibonacci($n-2);
}

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

				
			

14. Function to calculate area of circle

				
					<?php
function areaCircle($radius){
    return 3.1416 * $radius * $radius;
}

echo "Area: " . areaCircle(7);
?>

				
			

15. Function to return sum of array elements

				
					<?php
function arraySum($arr){
    return array_sum($arr);
}

$numbers = [10, 20, 30];
echo "Sum: " . arraySum($numbers);
?>

				
			

16. Function to convert Celsius to Fahrenheit

				
					<?php
function celsiusToFahrenheit($c){
    return ($c * 9/5) + 32;
}

echo "Fahrenheit: " . celsiusToFahrenheit(30);
?>

				
			

17. Function to check if number is even

				
					<?php
function isEven($num){
    return ($num % 2 == 0);
}

echo isEven(10) ? "Even Number" : "Odd Number";
?>

				
			

18. Function to capitalize first letter of each word

				
					<?php
function capitalizeWords($str){
    return ucwords($str);
}

echo capitalizeWords("hello php programming");
?>

				
			

19. Function to generate multiplication table

				
					<?php
function table($num){
    for($i=1; $i<=10; $i++){
        echo "$num x $i = " . ($num * $i) . "<br>";
    }
}

table(5);
?>

				
			

20. Function to return length of string

				
					<?php
function stringLength($str){
    return strlen($str);
}

echo "Length: " . stringLength("PHP Programming");
?>

				
			

21. Function to validate email format

				
					<?php
function validateEmail($email){
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

$email = "test@example.com";

echo validateEmail($email) ? "Valid Email" : "Invalid Email";
?>

				
			

22. Function to generate random password

				
					<?php
function generatePassword($length = 8){
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#";
    return substr(str_shuffle($chars), 0, $length);
}

echo "Generated Password: " . generatePassword(10);
?>

				
			

23. Function to check strong password

				
					<?php
function isStrongPassword($password){
    return preg_match('/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/', $password);
}

echo isStrongPassword("Test@123") ? "Strong Password" : "Weak Password";
?>

				
			

24. Function to remove duplicate values from array

				
					<?php
function removeDuplicates($arr){
    return array_unique($arr);
}

$data = [1,2,2,3,4,4];
print_r(removeDuplicates($data));
?>

				
			

25. Function to sort associative array by values

				
					<?php
function sortByValue($arr){
    asort($arr);
    return $arr;
}

$students = ["Amit"=>85, "Ravi"=>75, "Sita"=>90];
print_r(sortByValue($students));
?>

				
			

26. Function to calculate compound interest

				
					<?php
function compoundInterest($p, $r, $t){
    return $p * pow((1 + $r/100), $t);
}

echo "Amount: " . compoundInterest(1000, 5, 2);
?>

				
			

27. Function to sanitize user input

				
					<?php
function sanitizeInput($data){
    return htmlspecialchars(trim($data));
}

$input = "<script>alert('hack')</script>";
echo sanitizeInput($input);
?>

				
			

28. Function to check if string contains substring

				
					<?php
function contains($string, $search){
    return strpos($string, $search) !== false;
}

echo contains("Hello PHP", "PHP") ? "Found" : "Not Found";
?>

				
			

29. Function to flatten multidimensional array

				
					<?php
function flattenArray($array){
    $result = [];

    foreach($array as $value){
        if(is_array($value)){
            $result = array_merge($result, flattenArray($value));
        } else {
            $result[] = $value;
        }
    }
    return $result;
}

$data = [1, [2,3], [4,[5,6]]];
print_r(flattenArray($data));
?>

				
			

30. Function to calculate age from DOB

				
					<?php
function calculateAge($dob){
    $birthDate = new DateTime($dob);
    $today = new DateTime();
    return $today->diff($birthDate)->y;
}

echo "Age: " . calculateAge("2000-05-10");
?>

				
			

31. Function to generate slug (SEO-friendly URL)

				
					<?php
function generateSlug($text){
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    return trim($text, '-');
}

echo generateSlug("Learn PHP Programming Fast!");
?>

				
			

32. Function to paginate array data

				
					<?php
function paginate($data, $page, $limit){
    $offset = ($page - 1) * $limit;
    return array_slice($data, $offset, $limit);
}

$data = range(1,50);
print_r(paginate($data, 2, 10));
?>

				
			

33. Function to encrypt password (hashing)

				
					<?php
function hashPassword($password){
    return password_hash($password, PASSWORD_DEFAULT);
}

echo hashPassword("mypassword");
?>

				
			

34. Function to verify hashed password

				
					<?php
function verifyPassword($password, $hash){
    return password_verify($password, $hash);
}

$hash = password_hash("12345", PASSWORD_DEFAULT);

echo verifyPassword("12345", $hash) ? "Match" : "Not Match";
?>

				
			

35. Function to find second largest number in array

				
					<?php
function secondLargest($arr){
    rsort($arr);
    return $arr[1];
}

$data = [10, 20, 50, 40];
echo "Second Largest: " . secondLargest($data);
?>

				
			

36. Function to check palindrome number

				
					<?php
function isPalindromeNumber($num){
    return $num == strrev($num);
}

echo isPalindromeNumber(121) ? "Palindrome" : "Not Palindrome";
?>

				
			

37. Function to merge and sort arrays

				
					<?php
function mergeSortArrays($a, $b){
    $merged = array_merge($a, $b);
    sort($merged);
    return $merged;
}

print_r(mergeSortArrays([5,2], [3,1]));
?>

				
			

38. Function to count word frequency

				
					<?php
function wordFrequency($text){
    $words = explode(" ", strtolower($text));
    return array_count_values($words);
}

print_r(wordFrequency("php is easy php is powerful"));
?>

				
			

39. Function to validate mobile number (India)

				
					<?php
function validateMobile($number){
    return preg_match('/^[6-9]\d{9}$/', $number);
}

echo validateMobile("9876543210") ? "Valid" : "Invalid";
?>

				
			

40. Function to create JSON response (API-style)

				
					<?php
function jsonResponse($data){
    header("Content-Type: application/json");
    return json_encode($data);
}

$data = ["status"=>"success", "message"=>"Data fetched"];
echo jsonResponse($data);
?>