How to Use Functions in PHP

0
486
Functions in PHP
Today we will learn how to use Functions in PHP in the series of PHP Program for beginners. This PHP Programming Tutorial will help you to grasp the concept strongly. So, without wasting any time, let’s get into it.

What are Functions in PHP?

  • Functions Divide our code into blocks.
  • Saves our time by allowing code reusability ( Which means, you can write a code in one block and then you can call it anywhere in your program, N number of times)
  • A function can return Values by using ‘return’ statement
  • Functions can be of 2 types – User Defined and Pre Defined
  • Function is declared using ‘function’ keyword
  • Function Names are case insensitive

Syntax For Using Functions in PHP

function function_name(Arguments){
******Code********
******Code********
}

Learn: Factorial Program by Taking User Input

Example Program for using Functions in PHP

<?php
//Finding Factorial Using Functions

facto(5); //Function is called here. We are sending 5 to factorial
facto(6); // 6 is being sent to function

function facto($n){

$fact=1;
for($i=1;$i<=$n;$i++)
$fact=$fact*$i;
echo $fact.”<br> “;
}

?>

Functions in PHP
Functions in PHP

The function recieves values and do the processing.We are printing the result using function itself but we can also send the processed value back to that place, from where our function was called. Using Return Statement.

Learn: Associative Arrays in PHP

How to use Return Statement in PHP

<?php
//Finding Factorial Using Functions

$n= facto(5); //Explanation
echo $n;

function facto($n){

$fact=1;
for($i=1;$i<=$n;$i++)
$fact=$fact*$i;
return $fact;
}

?>

Explaination: 5 is passed to the function named facto. Function recieves value and process it. At last statement, the function returns some value back to the calling code. The returned value is then assigned to variable $n and then we simply print it.

Using Return Statement in PHP
Using Return Statement in PHP

So this is it for today guys in the basics of using functions in PHP. Next, we will cover 2 3 Example Programs and then we will see some Array Functions. If you stick with us, you will learn a lot of PHP Programming in such great way with a lot of Example Programs and Code Explanation (Our target is: To make codes easy). Subscribe to the newsletter to get such PHP Tutorials updates into your mailbox. Take Care and Keep Learning.

LEAVE A REPLY

Please enter your comment!
Please enter your name here