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..??
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With