0

What I'm trying to do is write one function to reuse vs writing out an if statement every time.

If statement:

if (!isset($value)){ echo 'null';}else{ echo $value;}

Function:

function isSetTest($value){
    if ( !isset($value)){
       $value = NULL;
    }
    return $value;
}

echo'name'.isSetTest($value);

Function works but I still get the "undefined" error message which is what i'm trying to avoid.

4
  • Pass the variable name as string an use variable variables Commented Jun 24, 2015 at 22:11
  • The function is returning $value regardless of anything. And whats going on with $field? that doesn't go anywhere either. Commented Jun 24, 2015 at 22:11
  • Sorry fixed the "$field". yes it will return the $value if its there if its not then its set to null vs undefined. Commented Jun 24, 2015 at 22:13
  • Is there actually an array involved? Commented Jun 24, 2015 at 22:39

2 Answers 2

1

Pass by reference instead, so that no processing of the variable is done until you want it:

function isSetTest(&$value) { // note the &
    if (!isset($value)) {
       $value = NULL;
    }
    return $value;
}

You can shorten this a bit:

function isSetTest(&$value) {
    return isset($value) ? $value : null;
}

I have a function that does something similar, except you can provide an optional default value in the case that the variable is not set:

function isset_or(&$value, $default = null) {
    return isset($value) ? $value : $default;
}
Sign up to request clarification or add additional context in comments.

Comments

0

The problem in your code is, that you still pass an undefined variable to your function, so that's why you still get your undefined error.

One way to solve this now, is that you pass your variable name as a string and then use variable variables, to check if it exists, e.g.

function isSetTest($value){
    global $$value;
    if ( !isset($$value)){
       $$value = NULL;
    }
    return $$value;
}

echo'name'.isSetTest("value");

Demo

1 Comment

The problem with using global is that the variable must, obviously, be in the global scope for it to work, which it (hopefully) won't be in 99% of cases.

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.