Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Use isset inside function not working..?

Tags:

function

php

I have a PHP script that when loaded, check first if it was loaded via a POST, if not if GET['id'] is a number.

Now I know I could do this like this:

if(isset($_GET['id']) AND isNum($_GET['id'])) { ... }

function isNum($data) {  
    $data = sanitize($data);
    if ( ctype_digit($data) ) {
        return true;
    } else {
        return false;
    }
}

But I would like to do it this way:

if(isNum($_GET['id'])) { ... }

function isNum($data) {  
    if ( isset($data) ) {
        $data = sanitize($data);
        if ( ctype_digit($data) ) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

When I try it this way, if $_GET['id'] isn't set, I get a warning of undefined index: id... It's like as soon as I put my $_GET['id'] within my function call, it sends a warning... Even though my function will check if that var is set or not...

Is there another way to do what I want to do, or am I forced to always check isset then add my other requirements..??

like image 583
pnichols Avatar asked Jun 14 '10 15:06

pnichols


People also ask

Does isset () function do in PHP?

Definition and Usage. The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

What can I use instead of isset in PHP?

The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.

What is if isset ($_ POST submit )) in PHP?

Use isset() method in PHP to test the form is submitted successfully or not. In the code, use isset() function to check $_POST['submit'] method. Remember in place of submit define the name of submit button. After clicking on submit button this action will work as POST method.

Can I use empty instead of isset?

The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not. The isset() function will generate a warning or e-notice when the variable does not exists. The empty() function will not generate any warning or e-notice when the variable does not exists.


1 Answers

I always include a convenience function that a few other languages provide: get.

function get($needle, $haystack, $return=null) {
    return array_key_exists($needle, $haystack) ? $haystack[$needle] : $return;
}

Now you can call:

if(isNum(get('id', $_GET))) {
    // do something here
}
like image 101
thetaiko Avatar answered Sep 23 '22 02:09

thetaiko