DEV Community

Md Jannatul Nayem
Md Jannatul Nayem

Posted on

What is function in context of PHP?

A function is a bunch of codes that solve a particular problem and solve perfectly. It is encapsulated such a way so that user can use the same code again and again without copy pasting.

Or you can think a function is a kind of machine. It may or not take some input/inputs and may or not return some output. Think like a blender machine. It takes input such as some mixed fruits, sugar, salt, water and It blends perfectly and then it return a glass of fruit juice. Sometimes inputs are considered as parameters. But it is not necessary that a function must take input or it must return some data. Think like a calling bell. When you press or call it it just creates a sound. There is no return.

A function name should be meaningful so that anybody can guess what it actually does.

Suppose you need to list all prime numbers from a given range [a, b] frequently. To filter out prime numbers you have to first detect if the number is prime but you need to check it for each number. So you can write a function to check if the number is prime.

Here is a function that can solve this problem:

<?php

function is_prime($n){
    if ($n < 2){
        return false;
    }
    if($n == 2){
        return true;
    }
    if($n % 2 == 0){
        return false;
    }
    for($i = 3; $i <= (int)sqrt($n); $i += 2){
        if ($n % $i == 0){
            return false;
        }
    }
    return true;
}

$prime_list = [];
$a = 1;
$b = 10;
for($i = $a; $i <= $b; $i++){
    if(is_prime($i)){
       $prime_list[] = $i;
    }
}
print_r($prime_list);


Enter fullscreen mode Exit fullscreen mode

Now you can use this is_prime function for any range without copy pasting. Just call the function with necessary parameters.

Top comments (0)