I need to check if variables are set to something. Up till now I have been using strlen(), but that is really embarrassing as I am pretty sure that is not a very efficient function to be using over an over again.
How do I perform this sort of check more efficiently:
if (strlen($_GET['variable']) > 0)
{
Do Something
}
Note that I don't want it to do anything if $_GET['variable'] = ''
Just to clarify what I mean - If I had www.example.com?variable=&somethingelse=1
I wouldn't want it to penetrate that if statement
Determine if a variable is considered set, this means if a variable is declared and is different than null . If a variable has been unset with the unset() function, it is no longer considered to be set. isset() will return false when checking a variable that has been assigned to null .
to check if your script was POSTed. If additional data was passed, $_POST will not be empty, otherwise it will. You can use empty method to check if it contains data. Since $_POST always exists if ($_POST) will do just fine, no need for empty .
You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL.
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>
You can try empty
.
if (!empty($_GET['variable'])) {
// Do something.
}
On the plus side, it will also check if the variable is set or not, i.e., there is no need to call isset
seperately.
There is some confusion regarding not calling isset
. From the documentation.
A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
and...
That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
if(isset($_GET['variable']) && $_GET['variable']!=""){
}
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