2

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 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

all i did was literally add an & to the front of each variable in the function and it worked now. didnt have to change anything else. it works exactly the same as javascript, i just didnt know how to pass it i guess, thanks for the help!
@user3783243 I am aware but the use of global is discouraged for many reasons.
@user3783243 I upvoted your comment for the suggestion and edited my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.