asDca21
asDca21

Reputation: 161

Why pass by refrance makes notice message in php?

I'm trying to use the following function in PHP to echo the variable if it's already been set or echo the alternate text:

function _echo(&$var, $alt = ''){
    if ( isset($var) ){
        echo $var;
    } else {
        echo $alt;
    }
}

And the following code to call the function. Note that $plan is not defined before:

<input type="text" name="test" value="<?= _echo($plan['program']) ?>">

But it triggers:

Notice: Undefined index: program in [file] on line [line]

I tried the following code to find out the problem and it was unexpected, $plan was defined when function is being called:

var_dump($plan);
<input type="text" name="test" value="<?= _echo($plan['test']) ?>">
var_dump($plan);

And the output was:

Notice: Undefined variable: plan in [file] on line [line] Notice:

Undefined index: program in [file] on line [line] >> Here NULL was echoed

array(1) { ["program"]=> NULL }

What is the problem exactly and how can I make such a function?

Upvotes: 0

Views: 45

Answers (1)

Jirka Hrazdil
Jirka Hrazdil

Reputation: 4021

The problem is not in passing argument by reference, but rather in referencing array index that does not exist or variable that does not exist. You would have to use isset():

<input type="text" name="test"
value="<?= _echo(isset($plan['program']) ? $plan['program']: '') ?>">

Upvotes: 1

Related Questions