PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 6.6 Creating Functions That Take a Variable Number of Arguments

6.6.1 Problem

You want to define a function that takes a variable number of arguments.

6.6.2 Solution

Pass an array and place the variable arguments inside the array:

// find the "average" of a group of numbers
function mean($numbers) {
    // initialize to avoid warnings
    $sum = 0;

    // the number of elements in the array
    $size = count($numbers);

    // iterate through the array and add up the numbers
    for ($i = 0; $i < $size; $i++) {
        $sum += $numbers[$i];
    }

    // divide by the amount of numbers
    $average = $sum / $size;

    // return average
    return $average;
}

$mean = mean(array(96, 93, 97));

6.6.3 Discussion

There are two good solutions, depending on your coding style and preferences. The more traditional PHP method is the one described in the Solution. We prefer this method because using arrays in PHP is a frequent activity; therefore, all programmers are familiar with arrays and their behavior.

So, while this method creates some additional overhead, bundling variables is commonplace. It's done in Recipe 6.5 to create named parameters and in Recipe 6.8 to return more than one value from a function. Also, inside the function, the syntax to access and manipulate the array involves basic commands such as $array[$i] and count($array).

However, this can seem clunky, so PHP provides an alternative and allows you direct access to the argument list:

// find the "average" of a group of numbers
function mean() {
    // initialize to avoid warnings
    $sum = 0;

    // the number of arguments passed to the function
    $size = func_num_args();

    // iterate through the arguments and add up the numbers
    for ($i = 0; $i < $size; $i++) {
        $sum += func_get_arg($i);
    }

    // divide by the amount of numbers
    $average = $sum / $size;

    // return average
    return $average;
}

$mean = mean(96, 93, 97);

This example uses a set of functions that return data based on the arguments passed to the function they are called from. First, func_num_args( ) returns an integer with the number of arguments passed into its invoking function — in this case, mean( ). From there, you can then call func_get_arg( ) to find the specific argument value for each position.

When you call mean(96, 93, 97), func_num_args( ) returns 3. The first argument is in position 0, so you iterate from 0 to 2, not 1 to 3. That's what happens inside the for loop where $i goes from 0 to less than $size. As you can see, this is the same logic used in the first example in which an array was passed. If you're worried about the potential overhead from using func_get_arg( ) inside a loop, don't be. This version is actually faster than the array passing method.

There is a third version of this function that uses func_num_args( ) to return an array containing all the values passed to the function. It ends up looking like hybrid between the previous two functions:

// find the "average" of a group of numbers
function mean() {
    // initialize to avoid warnings
    $sum = 0;

    // load the arguments into $numbers
    $numbers = func_get_args();

    // the number of elements in the array
    $size = count($numbers);

    // iterate through the array and add up the numbers
    for ($i = 0; $i < $size; $i++) {
        $sum += $numbers[$i];
    }

    // divide by the amount of numbers
    $average = $sum / $size;

    // return average
    return $average;
}

$mean = mean(96, 93, 97);

Here you have the dual advantages of not needing to place the numbers inside a temporary array when passing them into mean( ), but inside the function you can continue to treat them as if you did. Unfortunately, this method is slightly slower than the first two.

6.6.4 See Also

Recipe 6.8 on returning multiple values from a function; documentation on func_num_arg( ) at http://www.php.net/func-num-arg, func_get_arg( ) at http://www.php.net/func-get-arg, and func_get_args( ) at http://www.php.net/func-get-args.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    6.1 Introduction
    Recipe 6.2 Accessing Function Parameters
    Recipe 6.3 Setting Default Values for Function Parameters
    Recipe 6.4 Passing Values by Reference
    Recipe 6.5 Using Named Parameters
    Recipe 6.6 Creating Functions That Take a Variable Number of Arguments
    Recipe 6.7 Returning Values by Reference
    Recipe 6.8 Returning More Than One Value
    Recipe 6.9 Skipping Selected Return Values
    Recipe 6.10 Returning Failure
    Recipe 6.11 Calling Variable Functions
    Recipe 6.12 Accessing a Global Variable Inside a Function
    Recipe 6.13 Creating Dynamic Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele