Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if php get variable is set to anything?

Tags:

php

get

strlen

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

like image 926
Amy Neville Avatar asked Jun 08 '13 12:06

Amy Neville


People also ask

Which function is used to check whether a variable is already set or not?

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 .

Is $_ POST always set?

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 .

How do you check if a variable is undefined in PHP?

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.

What is $_ GET in PHP?

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>


2 Answers

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.

like image 199
hw. Avatar answered Oct 19 '22 08:10

hw.


 if(isset($_GET['variable']) && $_GET['variable']!=""){

}
like image 7
Srikanth Kolli Avatar answered Oct 19 '22 09:10

Srikanth Kolli