PHp function - testing if my variable exists and if condition is met
I would like to create a php function. Basically, this is what I have:
if(isset($myvariable) AND $myvariable == "something")
{
echo 'You can continue';
}
and what i want:
if(IssetCond($myvariable, "something"))
{
echo 'You can continue';
}
I need a function that checks if a variable exists and if it checks if a condition is met. Otherwise, it returns false.
I've tried a lot of things, but I still have a problem where $ myvariable doesn't exist.
function IssetCond($var, $value){
if(isset($var) AND $var == $value)
{
return true;
}
else
{
return false;
}
}
When $ myvariable exists and whether the condition is true or not, it works.
If you have a few minutes to help me, I will be grateful.
thank
Thomas
source to share
Your idea is good, but if you pass a variable to your function, you pass the value of that variable to your function. If your variable is not set before you get the error you are trying to prevent with your function.
You can pass a reference to a function, but it will cause the same problem if you don't set the variable before.
source to share
I think I found the answer, thanks to @Teko
$a = "3";
function IssetCond($var, $value){
global $$var;
if (isset($$var) && $$var == $value)
{ return true;}
return false;
}
if(IssetCond('d', 4))
{
echo 'first test'; // wont display
}
if(IssetCond("a", 3))
{
echo 'second test'; // will display
}
if(IssetCond("a", 4))
{
echo 'third test'; // wont display
}
Thanks everyone!
source to share