Thursday, 6 June 2013

Arbitrary Number of Function Arguments in PHP


In PHP there is a method to pass arbitrary number of function arguments.

For Example:

<?php
function my_function() {

    $arguments = func_get_args();// returns an array of all passed arguments

    foreach ($arguments as $key => $value) {
        echo "State Name".($key+1).": $value<br/>";
    }

}
echo "Without argument<br/>";
$a = my_function();
print_r($a);
echo "<hr><br/>";

echo "Single argument<br/>";
$b = my_function('Delhi');
print_r($b);
echo "<hr><br/>";

echo "Multiple argument call<br/>";
$c = my_function('Delhi','Mumbai','Uttrakhand');
print_r($c);
?>

Output:
Without argument


Single argument
State Name1: Delhi


Multiple argument call
State Name1: Delhi
State Name2: Mumbai
State Name3: Uttrakhand

No comments: