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?