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.
2
Answers
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 :
you pass 1 or x arguments, almost without worrying about what you will send or receive…
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
You can make a parameter optional like this:
This will return: