0

I'm trying to write a function to check if my variables are valid. For example, in my script I have:

$flag = $_GET['page'];

But then I get the error:

Notice: Undefined index: page in C:\xampp\htdocs\phpinv\php\add.php on line 8

I tried writing a checkVar function:

function checkVar($var, $method, $defaultValue){
    if (!isset($method['$var'])) 
    {
        $var = $defaultValue;
    } else {
        $var = $method['$var'];
    }
}

But then I get:

Parse error: syntax error, unexpected '[' in C:\xampp\htdocs\phpinv\php\functions.php on line 21
3
  • 1
    Is that the whole body of the function? It seems pointless. $var is not a reference and yet the function is not returning anything. Commented Apr 15, 2012 at 9:04
  • the provided code has no line 21, so the parse error probably is outsie the function Commented Apr 15, 2012 at 9:05
  • I didn't include the full source. Commented Apr 15, 2012 at 9:19

2 Answers 2

1

Addressing '$var' in your array uses '$var' as a string and not the value stored in $var.

This is probably what you want:

function checkVar($var, $method, $defaultValue){ 
    if (!isset($method[$var]))  
    { 
        $var = $defaultValue; 
    } else { 
        $var = $method[$var]; 
    } 
} 
Sign up to request clarification or add additional context in comments.

Comments

1

may be you should do something like this

    function checkVar($var, $method, $defaultValue){
        if (!isset($method[$var])) //instead of $method['$var']
        {
            $var = $defaultValue;
        } else {
            $var = $method[$var];
        }
        return $var;
    }

2 Comments

This and your checkVar function should be returning $var.
well true, makes sense. Edited !

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.