DEV Community

Md Jannatul Nayem
Md Jannatul Nayem

Posted on

1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay