Question

So I have a variable and a function that doesn't work to demonstrate my thought process.

Code:

    $variable = "This is a string!";

    function is($var)
    {
      if( isset ( $var ) )
        return true;
      return false;
    }

    if( is ( $variable ) )
      echo "This variable exists!";
    else
      echo "This variable does not exist!";

Output:

    This variable exists!

Because $variable exists, the function will work correctly but there is an issue when $variable has not been set or defined.

Code:

    function is($var)
    {
      if( isset ( $var ) )
        return true;
      return false;
    }

    if( is ( $variable ) )
      echo "This variable exists!";
    else
      echo "This variable does not exist!";

Output:

      Notice: Undefined variable: variable on line x
      This variable does not exist!

Because the variable is not defined yet, when it is being referenced PHP will return a notice saying this variable you attempted to reference is undefined. This is an issue because the function always creates a notice when the variable is not properly set, which is was trying to avoid in the first place.

So I tried passing the variable name as a string without the reference.

Code:

    $variable = "This is a string";

    function is($string)
    {
      if(isset($$string)) // Variable Variables
        return $$string;
      return "";
    }

    echo is("variable");

But this still did not work. I am out of ideas on how to gracefully output something using a short function instead of typing this every time:

    echo (isset($variable) ? $variable : "");

How can I check if a reference exists or not using php?

Was it helpful?

Solution

Prepend the variable/parameter being tested with the error control operator "@". This suppresses any errors in the expression - such as the variable not existing:

test(@$bar);


function test($foo)
{
    if(isset($foo))
        echo "A";
    else
        echo "B";
}

OTHER TIPS

you just need to add @ to your variable to avoid showing up errors

you can change your code like this:

$variable = "This is a string!";
function is($var)
{
  if( isset ( $var ) )
    return true;
  return false;
}

if( is ( @$variable ) )
  echo "This variable exists!";
else
  echo "This variable does not exist!";

you can find that i've changed if( is ( $variable ) ) to this if( is ( @$variable ) )

You need to check isset($variable) before calling the function with the var. Maybe not as convenient as you want, but that's how it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top