"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Sunday, September 1, 2024

Class 9: Functions - Part 2

 

Class 9: Functions - Part 2


Objective:

Understand function arguments, default values, and variable-length arguments.

Learn to use anonymous functions.

Outcome:

Students will be able to write functions with default and variable-length arguments, and utilize anonymous functions for short-term operations.

1. Function Arguments in PHP

In PHP, functions can accept one or more arguments. These arguments are the inputs to the function, allowing you to pass data into the function when you call it.

Example:

<?php

function sayHello($name) {

    echo "Hello, $name!";

}

sayHello("Alice");  // Output: Hello, Alice!

?>

In this example, the function sayHello() accepts a single argument $name and uses it to print a greeting.


2. Default Argument Values

PHP allows you to define default values for function arguments. This means if the caller does not provide a value, the function will use the default value.

Example:

<?php

function greet($name = "Guest") {

    echo "Hello, $name!";

}

greet();          // Output: Hello, Guest!

greet("Alice");   // Output: Hello, Alice!

?>

In this example, if no argument is passed to the greet() function, it defaults to "Guest."


Points to Remember:

Default values are specified in the function declaration.

Default values must be at the end of the argument list.

3. Variable-Length Argument Lists (Variadic Functions)

Sometimes, you may want a function to accept a variable number of arguments. PHP allows you to handle this with the ... operator, also known as the splat operator.

Example:

<?php

function sum(...$numbers) {

    $total = 0;

    foreach ($numbers as $number) {

        $total += $number;

    }

    return $total;

}

echo sum(1, 2, 3, 4);  // Output: 10

?>

Explanation:

The function sum() can accept any number of arguments.

Inside the function, $numbers is treated as an array containing all the arguments passed to the function.

4. Anonymous Functions (Lambdas/Closures)

Anonymous functions, also known as closures or lambda functions, are functions that have no name. They are often used for short-term tasks, such as callbacks or when a function is only needed temporarily.

Example:

<?php

$square = function($n) {

    return $n * $n;

};

echo $square(4);  // Output: 16

?>

Explanation:

The function is assigned to the variable $square.

It can be called just like any other function, but it is unnamed.

Using Anonymous Functions with Array Functions:

Anonymous functions are often used with PHP's array functions, such as array_map, array_filter, and usort.

Example:

<?php

$numbers = [1, 2, 3, 4, 5];

$squaredNumbers = array_map(function($n) {

    return $n * $n;

}, $numbers);

print_r($squaredNumbers);  // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )

?>

Explanation:

The array_map() function applies the anonymous function to each element of the array $numbers, returning a new array with the squared values.

Conclusion:

By understanding and utilizing function arguments, default values, variable-length arguments, and anonymous functions, you can write more flexible, reusable, and efficient PHP code.

Assignments

Assignment 1: Greeting with Default and Custom Name

Task:

Create a function greetUser that accepts a name as an argument and has a default value of "Visitor." If no name is provided, it should greet the user with "Hello, Visitor!". If a name is provided, it should greet the user with "Hello, [Name]!".

Example:

<?php

function greetUser($name = "Visitor") {

    echo "Hello, $name!<br>";

}

greetUser();          // Output: Hello, Visitor!

greetUser("Alice");   // Output: Hello, Alice!

?>

Assignment 2: 

Summing Numbers with a Variable-Length Argument List

Task:

Write a function calculateSum that accepts a variable number of arguments and returns the sum of those numbers.

Example:

<?php

function calculateSum(...$numbers) {

    $total = 0;

    foreach ($numbers as $number) {

        $total += $number;

    }

    return $total;

}

echo calculateSum(1, 2, 3);         // Output: 6

echo calculateSum(10, 20, 30, 40);  // Output: 100

?>

Assignment 3: 

Multiply Numbers Using Anonymous Function

Task:

Use an anonymous function within an array_map to create a new array where each element is the result of multiplying the corresponding element in the original array by 2.

Example:

<?php

$numbers = [1, 2, 3, 4, 5];

$multipliedNumbers = array_map(function($n) {

    return $n * 2;

}, $numbers);

print_r($multipliedNumbers);  // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )

?>

Assignment 4: 

Find the Maximum Value

Task:

Create a function findMaxValue that accepts a variable number of arguments and returns the maximum value.

Example:

<?php

function findMaxValue(...$values) {

    return max($values);

}

echo findMaxValue(1, 3, 7, 2);     // Output: 7

echo findMaxValue(10, 20, 5, 15);  // Output: 20

?>

Assignment 5: 

Filter Even Numbers

Task:

Write a script that uses an anonymous function within array_filter to filter out only even numbers from an array.

Example:

<?php

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$evenNumbers = array_filter($numbers, function($n) {

    return $n % 2 == 0;

});

print_r($evenNumbers);  // Output: Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )

?>

Assignment 6: 

Reversing a String Using Anonymous Function

Task:

Create an anonymous function that reverses a string. Assign this function to a variable and use it to reverse different strings.

Example:

<?php

$reverseString = function($str) {

    return strrev($str);

};

echo $reverseString("hello");  // Output: olleh

echo $reverseString("PHP");    // Output: PHP

?>

Assignment 7: 

String Lengths Using Anonymous Function

Task:

Use an anonymous function within array_map to create a new array containing the lengths of the strings in the original array.

Example:

<?php

$words = ["apple", "banana", "cherry"];

$lengths = array_map(function($word) {

    return strlen($word);

}, $words);

print_r($lengths);  // Output: Array ( [0] => 5 [1] => 6 [2] => 6 )

?>

These assignments cover the key concepts of function arguments, default values, variable-length arguments, and anonymous functions, providing students with practical experience in using these features in PHP.


No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template