PHP take string and check if that string exists as a variable

╄→尐↘猪︶ㄣ 提交于 2019-12-01 22:18:31

I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:

function varIsset($var)
{   
    global $$var;
    return isset($$var) && !empty($$var);
}

Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.

Edit: If you need the value returned, you could do something like:

function valueVar($var)
{   
    global $$var;
    return (isset($$var) && !empty($$var)) ? $$var : NULL;
}

But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.

It would be a better approach to introduce a context in which you want to search, e.g.:

function varIsset($name, array $context)
{
    return !empty($context[$name]);
}

The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:

return isset($context[$name]) && strlen($name);

Try:

<?php
function varIsset($string){
  global $$string;
  return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!