Putting if statements inside php function with parameters?

Viewed 605

Im trying to put these if statements inside a php function to get results. So far its not working. I know this may be an easy solution, but I am new to PHP and the other examples that I looked at didnt help me a lot.
FUNCTION

$startdate='';
$enddate='12/3/2020';

function startEnd($startdate,$enddate){
    if($startdate==''){
        $startdate='Anytime';
    }
    if($enddate==''){
        $enddate='Anytime';
    }
}

CALL

startEnd($startdate,$enddate);

echo $startdate;
echo $enddate;
1 Answers

You cannot use variables that are outside of the scope of the function.

Once it is passed as an argument, in the function, it will be treated as a completely new variable. Unless you reintroduce them to the scope with global.

You can, however, pass a reference of a variable to a function using the & operator in the parameters.

function startEnd(&$string1, &$string2) {
    if ($string1 === '') {
        $string1 = 'Anytime';
    }
    if ($string2 === '') {
        $string2 = 'Anytime';
    }
}
startEnd($startdate, $enddate);
Related