PHP Programing language

adplus-dvertising
PHP FUNCTION-PARAMETER
Previous Home Next

The Function is using information to be send and use. The first function is Company Name isn't all that useful because all it does is to print out a single, unchanging string.If you want to use parameters, then you could be able to add some extra functionality.

A parameter always appearing with the parentheses "( )" and it looks just like a normal or simple PHP variable.

Let's create a new function that creating a custom greeting based on a person's name. If My parameter will be the person's name and My function will concatenate this name onto a greeting string. then Here's what the code would look like.

<?php
function myGreeting ($firstName){
    echo "Hello there ". $firstName . "!<br />";
}
?>

When we using Greeting function then we have to sending a string containing someone's name, otherwise it will break and when you are adding parameters, then you have to add more responsibility as a programmer. Let's call our new function with some common first names.

PHP Code:

<?php
function Greeting ($firstName)
{
    echo "My name is ". $firstName . "!<br />";
}
Greeting ("Amit");
Greeting ("Akash");
Greeting ("Abhay");
Greeting ("Abhinav");
?>

Output:

My name is Amit!
My name is Akash!
My name is Abhay!
My name is Abhinav!

If you use Multiple Parameter in function. Then separate multiple parameters PHP uses a comma ",". Let's modify our function to also include last names.

PHP Code:

<?php
function Greeting($firstName, $lastName){
    echo "My name is ". $firstName ." ". $lastName.
		"!<br />";
}
Greeting ("Amit", "singh");
Greeting ("Akash", "Pandey");
Greeting ("Abhay", "Saxena");
Greeting ("Abhinav", "Ojha");
?>

Output:

My name is Amit singh!
My name is Akash Pandey!
My name is Abhay Saxena!
My name is Abhinav Ojha!

PHP Function for reeturning value

The function information is being able to pass, then you can also have them return a value. However, then the a function can only return one thing, although that thing can be any integer, float, array, string, etc.

How does it return a value though? Well, when the function is used and finishes executing, it sort of changes from being a function name into being a value. To capture this value you can set a variable equal to the function.

$myVar = somefunction();

Example:

<?php
function Sum($X, $Y){
    $total = $X + $Y;
    return $total; 
}
$Number = 0;
echo "Before the function, Number = ". $Number."<br />";
$myNumber = Sum(10, 20); // Store the result of
Sum in $Number
echo "After the function, Number = " . $Number."<br />";
?>

Output:

Before the function, Number = 0
After the function, Number =30
Previous Home Next