Sam
Sam

Reputation: 376

Functions With Unlimited Arguments in php

I just want to make a function like array_merge ( array $array1 [, array $... ] ) or simple function like myfunc($st1, $st2, $st3, $st4, $st5, etc)

function make_my_merge($) {
     ..... operation to be performed ......
}

Upvotes: 2

Views: 425

Answers (4)

Anwar
Anwar

Reputation: 672

You would never know how many arguments you want... So you cannot define exact function with unlimited arguments in my opimion. But what I suggest is passing 2 arguments in a function, one as number of index or values in array and other the array itself.... It goes something like this

<?php
$arr = array('val1','val2','val3',.....);
$count = count($arr);
$result = your_function($count,$arr);
?> 

Your function would look like this which goes somewhere on the top or other php files or class

<?php
function your_function($count,$arr)
{
   //Here you know the number of values you have in array as $count
   //So you can use for loop or others to merge or for other operations
   for($i=0;$i<$count;$i++)
   {
          //Some operation
   }
}
?>

Upvotes: 0

Sampson
Sampson

Reputation: 268344

Use func_get_args() to access all arguments (as an array) passed to the function. Additionally, you can use func_num_args() to get a count of all arguments passed in.

function make_my_merge () {
    if ( func_num_args() ) {
        $args = func_get_args();
        echo join( ", ", $args );
    }
}

// Foo, Bar
make_my_merge("Foo", "Bar");

// Foo, Bar, Fizz, Buzz
make_my_merge("Foo", "Bar", "Fizz", "Buzz");

Codepad: http://codepad.org/Dk7MD18I

Upvotes: 4

bluevector
bluevector

Reputation: 3493

This should help: PHP Function Variable Arguments

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382696

Use func_get_args():

function make_my_merge() {
  $args = func_get_args();

  foreach ($args as $arg) {
    echo "Arg: $arg\n";
  }

}

As can be seen, you get all arguments passed to your function via func_get_args() function which returns an array you can iterate over using each to work on each argument passed.

Upvotes: 0

Related Questions