$s = "text";
$exploded_s = explode('/', $s);
//$s2 = isset_or($exploded_s[1], "empty"); //This shows notice Undefined offset: 1
$s2 = isset($exploded_s[1]) ? $exploded_s[1] : "empty"; //This is ok
echo $s2;

function isset_or($var, $val){
    return isset($var) ? $var : $val;
}

Both return "empty" but the first way also shows the notice. Why?

有帮助吗?

解决方案

You are passing $var by value - because it has none (and isn't set) you get the notice. However, if you pass by reference it will work.

function isset_or(&$var, $val){
    return isset($var) ? $var : $val;
}

其他提示

Because $exploded_s[1] is evaluated to pass the value to isset_or as your function specifies to pass the parameter by value.

When using isset, the value of $exploded_s[1] will not be evaluated, as it is passed by reference; essentially passing the memory address where the value of the second element on the array would be stored if it were not undefined.

Further information here: What's the difference between passing by reference vs. passing by value?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top