php Variables and Functions


 

php Variables and Functions

Most of the beginners always think, why we create functions and how does it help to the program? We create functions to make the program easier and smaller.

Most of the beginners always think, why we create functions and how does it help to the program? We create functions to make the program easier and smaller.

PHP Variables Functions( )

In this chapter we will learn about PHP functions( ). Most of the beginners always think, why we create functions and  how does it help to the program? We create functions to make the program easier and smaller. It prevents the programmer from writing the same code again and again. A program contains several functions that can be used several times .  A function escape the program from being complex and it compiles and run efficiently, which save the time of the programmer. It also makes the program easier. For defining a function we need to remember some important points:

(a) Always give name to the function. The function should start with name or underscores. It doesn't take numbers in the starting of the function name.  Such as  func_name, _funcname or name1.

(b) Don't forget the parentheses ( ).

(C) In between opening  and closing braces  return your statements.

Now, look at few examples and understand how functions are beneficial for a programmer.

Example 1:

<html>

<body>

<?php

function my_favorite( )

{

echo "Sachin Tendulkar";  /* statement  */

}

echo "My favorite cricket player is ";

myfavorite();

 ?>

</body>

</html>

The output of the above example is:

My favorite cricket player is Sachin Tendulkar

In this example, we give the name or define to a function called my_favorite( ). In the statement we written Sachin Tendulkar and then called the function after the closing braces.

PHP Function - Passing Parameters ( )

PHP function also provides the facility to pass the parameters in the program. It means we are adding more functionality in our program. It is similar to the variable and you can fetch as much as information you want. For example :

<html>

<body>

<?php

function func_name($name)

{

echo $name . " " . " Tendulkar " . "<br/>";

0

}

echo "My name is ";

func_name("Sachin");

1

echo "My younger brother name is ";

func_name("Vijay");

echo "My elder brother name is ";

2

func_name("Ajay");

?>

</body>

3

</html>

In this example we are passing parameters in the parentheses.

PHP Functions - Return value ( )

4

With the help of return statement in PHP we can ask the program to return some value either in the form of int, float, array, string etc which one you are looking for.

<html>

<body>

5

<?php

function sum($num1,$num2)

{

6

$total = $num1 + $num2;

return $total;

}

7

$num1 = "100";

$num2 = "200";

echo  " $num1 + $num2 = " . $total = sum($num1,$num2);

8

?>

</body>

</html>

9

 

Ads