How To pass infinite argument in PHP function?

There are many ways to pass undefined no of arguments in a function. Mostly I use one of these three ways:-

  • Pass all the Argument in the form of an array
function sum(array $args){
    $sum = 0;
    
    if( is_numeric( implode("", $args) ) ) 
        {
            foreach($args as $arg){
                $sum += $arg;
                }
            return $sum;
        }
  return "Only array with numeric value accepted";
    
}

// if input is an array with values 1, 2, 3, 5
print_r ( sum([1, 2, 3, 5]) );

//output is 11
  • Use func_get_args () to get all the passed argument
function makeUrl() {
$args = func_get_args();
  $url = 'https://www.maxester.com/blog/';
  $imp = implode('-', array_filter($args) );
  return $url.lcreplace( $imp ) ;
}

function lcreplace($url) {
return str_replace( "--", "-", preg_replace('/[^A-Za-z0-9-]/', "-", strtolower($url) ) );
}

// input
print_r( makeUrl( "How", "To", "pass", "infinite", "argument", "in", "PHP" ) );
  
//output
https://www.maxester.com/blog/how-to-pass-infinite-argument-in-php
  • Use PHP Spread Operator( […$array] )
function makeUrl(...$args) {

  $url = 'https://www.maxester.com/blog/';
  $imp = implode('-', array_filter($args) );
  return $url.lcreplace( $imp ) ;
}

function lcreplace($url) {
return str_replace( "--", "-", preg_replace('/[^A-Za-z0-9-]/', "-", strtolower($url) ) );
}


// input
print_r( makeUrl( "How", "To", "pass", "infinite", "argument", "in", "PHP" ) );
  
//output
https://www.maxester.com/blog/how-to-pass-infinite-argument-in-php

Each method mentioned above has its own advantages.

Leave a Reply

Your email address will not be published. Required fields are marked *