1

I'm trying to check if a variable is existing, and if not - then define it.

$checkarray = array($demo1, $demo2, $demo3);

foreach ($checkarray as $checkkey) {
  if (!isset($checkkey)) {
    $checkkey = 'none';
  }
}

But I'm just getting this error: *Notice: Undefined variable: demo1 (and so on...)

This is bascially what i'm trying to achive...

if (!isset($demo1)) {
  $demo1 = 'none';
 }

if (!isset($demo2)) {
  $demo2 = 'none';
 }

if (!isset($demo3)) {
 $demo3 = 'none';
}

But it's not pretty.

Any ideas?

Cheers Kris

3
  • 1
    Well you obviously can not put variables into an array that might not even exist ... What you could do, is put only the variable names or array keys to look for into an array that you then loop over ... but this would make more sense, if your input was in the form of an array already. Variable variables help you perform the check if you need this for real variables, and not arrays. Commented Aug 7, 2017 at 14:23
  • If you're just looking to see if the value exists, check out in_array Commented Aug 7, 2017 at 14:25
  • @CBroe you are right. Variable variables was the way to go. Thnx Commented Aug 7, 2017 at 14:44

1 Answer 1

1

You have to use the var name in your check array and not the var itself. This is called Variable variable

Then you can do something like this :

$checkarray = array('demo1', 'demo2', 'demo3');

foreach ($checkarray as $checkkey) {
  if (!isset($$checkkey)) {
    $$checkkey = 'none';
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.