Home > database >  Call PHP function with less parameters then expected by function
Call PHP function with less parameters then expected by function

Time:01-29

I have the following PHP function which is working very well:

<?php
function my_test_function($par1, $par2, $par3) {
    $string = $par1.$par2.$par3;
    return $string;
}

echo my_test_function('Hello', 'how are', 'you');
?>

But if I call the function like this:

echo my_test_function('Hello', 'how are');

I'll get an error message, because the function needs three parameters and I only send two parameters:

[29-Jan-2023 10:29:45 UTC] PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function my_test_function(), 2 passed in /home/user/public_html/test_file.php on line 7 and exactly 3 expected in /home/user/public_html/test_file.php:2
Stack trace:
#0 /home/user/public_html/test_file.php(7): my_test_function('Hello', 'how are')
#1 {main}
  thrown in /home/user/public_html/test_file.php on line 2

Is there a way to send less parameters than expected by the function? I'd like to call the function with two parameters, although tree are expected.

I know, I could just make the third parameter empty but this isn't my goal.

CodePudding user response:

You can make a parameter optional like this:

<?php
function my_test_function($par1, $par2, $par3 = "all of you") {
    $string = $par1.$par2.$par3;
    return $string;
}

echo my_test_function('Hello', 'how are', 'you');

echo my_test_function('Hello', 'how are');
?>

This will return:

Hellohow areyou
Hellohow areall of you

CodePudding user response:

if you want to use a function without knowing the number of arguments there is a technique that will please you, it is to use spread operators.
here is the link of the php doc
you can do write function like that :

function concatMyXStrings(...$strings){
    $out = '';
    foreach($strings as $string){
        $out .= $string;
    }
    return $out;
}

you pass 1 or x arguments, almost without worrying about what you will send or receive...

concatMyXStrings('I', ' ', 'love ', ' stack', ' ', ' !');
// or
concatMyXStrings('pink ', 'floyd');

you loop on it like an array to forge your string by concatenating at each iteration and normally, with that, you're saved!

edit : you can also use implode pour concatenation like this for avoid using a foreach loop

// ...
return implode('',$strings);
// ...
  • Related