Defining Functions

Started by chinmay.sahoo, 01-04-2016, 01:19:41

Previous topic - Next topic

chinmay.sahooTopic starter

There are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement:

Quotefunction some_function([arguments]) { code to execute; }

The brackets ([ ]) mean optional. The code could also be written with optional_ arguments in place of [arguments]. The function keyword is followed by the function name. Function names abide by the same rules as other named objects, such as variables, in PHP. A pair of parentheses (()) must come next. If your function has parameters, they're specified within the parentheses. Finally, the code to execute is listed between curly braces, as seen in the previous code example.


You can define functions anywhere in your code and call themfromvirtually anywhere. For the most part, all PHP variables . have only a single scope. A single scope spans included and required files as well. The function is defined on the same file or included in an include file. Functions can have parameters and return values that allow you to reuse code.

To create your own function that simply displays a different hello message, you would write:

Quote<?php
function hi( )
{
echo ("Hello from function-land!");
}
//Call the function
hi( );
?>

which displays:

Hello from function-land!

The hi function doesn't take any parameters, so you don't list anything between the parentheses. Now that you've defined a simple function, let's mix in some parameters.


TomClarke

#1
Here's an example of a function with parameters:

<?php
function greet($name)
{
    echo "Hello, " . $name . "! Welcome to function-land!" . PHP_EOL;
}
// Call the function
greet("Alice");
?>
This script would output:

Hello, Alice! Welcome to function-land!
In this function, "Alice" is an argument being passed to the greet function. The function takes this argument and incorporates it into the output message. You can replace "Alice" with any string value to customize the greeting.

It's also important to note that functions can accept multiple parameters:

<?php
function greet($name, $place)
{
    echo "Hello, " . $name . "! Welcome to ". $place ."!" . PHP_EOL;
}
// Call the function
greet("Alice", "Wonderland");
?>
This script would output:

Hello, Alice! Welcome to Wonderland!
In this version, the greet function takes two arguments: $name and $place. It uses both to construct a more specific welcome message.


we can take the concept of functions a bit further by discussing return values and scoping.

Return values are how functions give results back to the code that called them. Instead of (or in addition to) printing something out (like the examples above), functions often do some computation and then return the result. Here's an example:

<?php
function add($a, $b)
{
    return $a + $b;
}

// Call the function
$sum = add(3, 4);
echo $sum; // Outputs: 7
?>
In this case, the add function is taking two parameters ($a and $b), adding them together, and returning the result. When you call the add function with two numbers, it computes the sum and gives it back. We store this result in the $sum variable and then echo it.

Scoping refers to the visibility of variables in different parts of your code. In PHP, variables defined inside functions (like $a and $b above) can't be accessed outside of them, and by default, variables defined outside of functions can't be accessed inside them (unless they're passed as parameters). This concept is also known as variable scope. Here's an example to illustrate:

<?php
$x = "global x";

function test() {
    $x = "local x";
    echo $x;  // Outputs: local x
}

test();
echo $x;  // Outputs: global x
?>
In this case, even though there are two variables named $x, they are distinct because they exist in different scopes. The $x within test has a local scope, while the $x outside of test has a global scope.


Let's talk about Default Parameter Values and Variable-Length Argument Lists:

Default Parameter Values: You can set default values for your function parameters. This means that if a value is not provided when the function is called, these default values will be used.
Here's an example:

<?php
function greet($name = "World") {
    echo "Hello, " . $name . "!" . PHP_EOL;
}

greet();         // Outputs: Hello, World!
greet("Alice");  // Outputs: Hello, Alice!
?>
In this case, if greet is called without an argument, it uses "World" as the default value for $name.

Variable-Length Argument Lists: PHP also supports functions that can accept a variable number of arguments. This can be useful when it's unclear how many arguments your function might need. Since PHP 5.6, this functionality is implemented with the ... operator.
Here's an example using this concept:

<?php
function add_all(...$numbers) {
    $total = 0;
    foreach ($numbers as $n) {
        $total += $n;
    }
    return $total;
}

echo add_all(1, 2, 3, 4);           // Outputs: 10
echo add_all(1, 2, 3, 4, 5, 6, 7);  // Outputs: 28
?>
In this example, add_all accepts any number of arguments, adds them all together, and returns the result. The ...$numbers syntax in the function definition collects all the arguments into the $numbers array.

Together, these functionality enhance the flexibility and power of PHP functions, making it easier to create versatile and reusable blocks of code.


let's explore a few more concepts, including Associative Arrays, Loops, and Sorting:

Associative Arrays: In PHP, an array doesn't just have to be a simple list of items, it can also be an associative array - where you map keys to values. Here is how you might define an associative array:
<?php
$person = [
    "name" => "Alice",
    "age" => 25,
    "city" => "San Francisco"
];

echo $person["name"];  // Outputs: Alice
?>
Loops: Loops are a way to repeatedly execute some code. Here's a simple for loop in PHP:
<?php
for ($i = 0; $i < 5; $i++) {
    echo $i . PHP_EOL;
}
// This will output: 0, 1, 2, 3, 4 (each on a separate line)
?>
For each iteration of the loop, it will execute the code in the loop's body (here, echo $i . PHP_EOL;), then increment $i by one, then check whether $i < 5. As long as $i remains less than 5, it will keep looping.

Sorting: PHP includes several functions for sorting arrays. The most basic is sort(), which sorts an array in place. Here's how you might use it:
<?php
$values = [4, 2, 9, 6];

sort($values);

foreach ($values as $value) {
    echo $value . PHP_EOL;
}

// This will output: 2, 4, 6, 9 (each on a separate line)
?>
In this case, sort($values) sorts the array from lowest to highest. The foreach loop then prints out each value in the sorted array, one per line. Besides sort(), PHP also offers rsort() for reverse sorting, asort() and ksort() for sorting associative arrays by value and key respectively, and several other sorting functions.