PHP: Check if variable exist but also if has a value equal to something












30















I have (or not) a variable $_GET['myvar'] coming from my query string and I want to check if this variable exists and also if the value corresponds to something inside my if statement:



What I'm doing and think is not the best way to do:



if(isset($_GET['myvar']) && $_GET['myvar'] == 'something'): do something



My question is, exist any way to do this without declare the variable twice?



That is a simple case but imagine have to compare many of this $myvar variables.










share|improve this question




















  • 2





    PHP doesn't have a solution for this, but it's a programming language. You can (and ought to) always write a subprogram to shorten a repetitive code. Not to mention that in a good program every variable should be defined before use...

    – Your Common Sense
    Oct 24 '10 at 10:09


















30















I have (or not) a variable $_GET['myvar'] coming from my query string and I want to check if this variable exists and also if the value corresponds to something inside my if statement:



What I'm doing and think is not the best way to do:



if(isset($_GET['myvar']) && $_GET['myvar'] == 'something'): do something



My question is, exist any way to do this without declare the variable twice?



That is a simple case but imagine have to compare many of this $myvar variables.










share|improve this question




















  • 2





    PHP doesn't have a solution for this, but it's a programming language. You can (and ought to) always write a subprogram to shorten a repetitive code. Not to mention that in a good program every variable should be defined before use...

    – Your Common Sense
    Oct 24 '10 at 10:09
















30












30








30


4






I have (or not) a variable $_GET['myvar'] coming from my query string and I want to check if this variable exists and also if the value corresponds to something inside my if statement:



What I'm doing and think is not the best way to do:



if(isset($_GET['myvar']) && $_GET['myvar'] == 'something'): do something



My question is, exist any way to do this without declare the variable twice?



That is a simple case but imagine have to compare many of this $myvar variables.










share|improve this question
















I have (or not) a variable $_GET['myvar'] coming from my query string and I want to check if this variable exists and also if the value corresponds to something inside my if statement:



What I'm doing and think is not the best way to do:



if(isset($_GET['myvar']) && $_GET['myvar'] == 'something'): do something



My question is, exist any way to do this without declare the variable twice?



That is a simple case but imagine have to compare many of this $myvar variables.







php variables if-statement isset






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 14 '14 at 14:38









Michael Irigoyen

17.2k1575111




17.2k1575111










asked Oct 24 '10 at 9:51









Mariz MeloMariz Melo

3451917




3451917








  • 2





    PHP doesn't have a solution for this, but it's a programming language. You can (and ought to) always write a subprogram to shorten a repetitive code. Not to mention that in a good program every variable should be defined before use...

    – Your Common Sense
    Oct 24 '10 at 10:09
















  • 2





    PHP doesn't have a solution for this, but it's a programming language. You can (and ought to) always write a subprogram to shorten a repetitive code. Not to mention that in a good program every variable should be defined before use...

    – Your Common Sense
    Oct 24 '10 at 10:09










2




2





PHP doesn't have a solution for this, but it's a programming language. You can (and ought to) always write a subprogram to shorten a repetitive code. Not to mention that in a good program every variable should be defined before use...

– Your Common Sense
Oct 24 '10 at 10:09







PHP doesn't have a solution for this, but it's a programming language. You can (and ought to) always write a subprogram to shorten a repetitive code. Not to mention that in a good program every variable should be defined before use...

– Your Common Sense
Oct 24 '10 at 10:09














13 Answers
13






active

oldest

votes


















16














Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:



$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));


The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.



Or you can use something like that:



$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $m ) {
$_GET[$m] = null;
}


Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.



Update



One other way to clean up the code would be using a function that checks if the value is set.



function getValue($key) {
if (!isset($_GET[$key])) {
return false;
}
return $_GET[$key];
}

if (getValue('myvar') == 'something') {
// Do something
}





share|improve this answer


























  • Well I saw this around there, just hoping be possible without using arrays, thanks.

    – Mariz Melo
    Oct 24 '10 at 10:12











  • Updated my answer to show a possible way to do this without using another array.

    – mellowsoon
    Oct 24 '10 at 10:17











  • Thank you for the code Mellowsoon, back to work now.

    – Mariz Melo
    Oct 24 '10 at 10:35



















8














If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:



if ((isset($variable) ? $variable : null) == $value) { }


The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.






share|improve this answer





















  • 4





    It is better to suggest === than ==, as it will not have the downside you mention.

    – trincot
    Aug 18 '16 at 17:38



















1














As mellowsoon suggest, you might consider this approach:



required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $key => $default ) {
$_GET[$key] = $default ;
}


You put the default values and set the not recieved parameters to a default value :)






share|improve this answer































    0















    My question is, exist any way to do this without declare the variable twice?




    No, there is no way to do this correctly without doing two checks. I hate it, too.



    One way to work around it would be to import all relevant GET variables at one central point into an array or object of some sort (Most MVC frameworks do this automatically) and setting all properties that are needed later. (Instead of accessing request variables across the code.)






    share|improve this answer


























    • Just define all your variables. That's the point of all that mess.

      – Your Common Sense
      Oct 24 '10 at 10:05













    • Thank you Pekka, is really very boring do that.

      – Mariz Melo
      Oct 24 '10 at 10:14











    • Sometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.

      – Mariz Melo
      Oct 24 '10 at 10:15






    • 2





      @Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.

      – Pekka 웃
      Oct 24 '10 at 10:17













    • Pekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.

      – Mariz Melo
      Oct 24 '10 at 10:31



















    0














    Thanks Mellowsoon and Pekka, I did some research here and come up with this:




    • Check and declare each variable as null (if is the case) before start to use (as recommended):



    !isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;


    *ok this one is simple but works fine, you can start to use the variable everywhere after this line




    • Using array to cover all cases:



    $myvars = array( 'var1', 'var2', 'var3');
    foreach($myvars as $key)
    !isset($_GET[$key]) ? $_GET[$key] =0:0;


    *after that you are free to use your variables (var1, var2, var3 ... etc),



    PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);



    ... Better approaches are welcome :)





    UPDATE:



    Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.




    !isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;





    share|improve this answer

































      0














      why not create a function for doing this, convert the variable your want to check into a real variable, ex.



      function _FX($name) { 
      if (isset($$name)) return $$name;
      else return null;
      }


      then you do _FX('param') == '123', just a thought






      share|improve this answer


























      • this will still fire an error notice when you call _FX('param')

        – kmoney12
        Sep 17 '16 at 3:21



















      0














      I use all time own useful function exst() which automatically declare variables.



      Example -



      $element1 = exst($arr["key1"]);
      $val2 = exst($_POST["key2"], 'novalue');


      /**
      * Function exst() - Checks if the variable has been set
      * (copy/paste it in any place of your code)
      *
      * If the variable is set and not empty returns the variable (no transformation)
      * If the variable is not set or empty, returns the $default value
      *
      * @param mixed $var
      * @param mixed $default
      *
      * @return mixed
      */

      function exst( & $var, $default = "")
      {
      $t = "";
      if ( !isset($var) || !$var ) {
      if (isset($default) && $default != "") $t = $default;
      }
      else {
      $t = $var;
      }
      if (is_string($t)) $t = trim($t);
      return $t;
      }





      share|improve this answer
























      • Unfortunately this triggers a PHP notice if the array key doesn't exist, does it not?

        – Matt Browne
        Aug 10 '13 at 5:24



















      0














      A solution that I have found from playing around is to do:



      if($x=&$_GET["myvar"] == "something")
      {
      // do stuff with $x
      }





      share|improve this answer































        0














        <?php

        function myset(&$var,$value=false){
        if(isset($var)):
        return $var == $value ? $value : false;
        endif;
        return false;
        }

        $array['key'] = 'foo';

        var_dump(myset($array['key'],'bar')); //bool(false)

        var_dump(myset($array['key'],'foo'));//string(3) "foo"

        var_dump(myset($array['baz'],'bar'));//bool(false)





        share|improve this answer

































          0














          This is similar to the accepted answer, but uses in_array instead. I prefer to use empty() in this situation. I also suggest using the new shorthand array declaration which is available in PHP 5.4.0+.



          $allowed = ["something","nothing"];
          if(!empty($_GET['myvar']) && in_array($_GET['myvar'],$allowed)){..}


          Here is a function for checking multiple values at once.



          $arrKeys = array_keys($_GET);
          $allowed = ["something","nothing"];

          function checkGet($arrKeys,$allowed) {
          foreach($arrKeys as $key ) {
          if(in_array($_GET[$key],$allowed)) {
          $values[$key];
          }
          }
          return $values;
          }





          share|improve this answer

































            0














            As of PHP7 you can use the Null Coalescing Operator ?? to avoid the double reference:



            $_GET['myvar'] = 'hello';
            if (($_GET['myvar'] ?? '') == 'hello') {
            echo "hello!";
            }


            Output:



            hello!


            In general, the expression



            $a ?? $b


            is equivalent to



            isset($a) ? $a : $b





            share|improve this answer

































              -1














              Well, you could get by with just if($_GET['myvar'] == 'something') since that condition presumes that the variable also exists. If it doesn't, the expression will also result in false.



              I think it's ok to do this inside conditional statements like above. No harm done really.






              share|improve this answer


























              • And it fires a notice, if the myvar index doesn't exist.

                – erenon
                Oct 24 '10 at 12:30






              • 1





                True, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).

                – DanMan
                Oct 24 '10 at 12:35








              • 1





                Oof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.

                – Ross Snyder
                Oct 24 '10 at 21:38



















              -3














              No official reference but it worked when I tried this:



              if (isset($_GET['myvar']) == 'something')





              share|improve this answer



















              • 1





                Nope. This is comparing TRUE/FALSE against 'something'.

                – Dan H
                Sep 8 '14 at 11:25











              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4007752%2fphp-check-if-variable-exist-but-also-if-has-a-value-equal-to-something%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              13 Answers
              13






              active

              oldest

              votes








              13 Answers
              13






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              16














              Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:



              $required = array('myvar', 'foo', 'bar', 'baz');
              $missing = array_diff($required, array_keys($_GET));


              The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.



              Or you can use something like that:



              $required = array('myvar', 'foo', 'bar', 'baz');
              $missing = array_diff($required, array_keys($_GET));
              foreach($missing as $m ) {
              $_GET[$m] = null;
              }


              Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.



              Update



              One other way to clean up the code would be using a function that checks if the value is set.



              function getValue($key) {
              if (!isset($_GET[$key])) {
              return false;
              }
              return $_GET[$key];
              }

              if (getValue('myvar') == 'something') {
              // Do something
              }





              share|improve this answer


























              • Well I saw this around there, just hoping be possible without using arrays, thanks.

                – Mariz Melo
                Oct 24 '10 at 10:12











              • Updated my answer to show a possible way to do this without using another array.

                – mellowsoon
                Oct 24 '10 at 10:17











              • Thank you for the code Mellowsoon, back to work now.

                – Mariz Melo
                Oct 24 '10 at 10:35
















              16














              Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:



              $required = array('myvar', 'foo', 'bar', 'baz');
              $missing = array_diff($required, array_keys($_GET));


              The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.



              Or you can use something like that:



              $required = array('myvar', 'foo', 'bar', 'baz');
              $missing = array_diff($required, array_keys($_GET));
              foreach($missing as $m ) {
              $_GET[$m] = null;
              }


              Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.



              Update



              One other way to clean up the code would be using a function that checks if the value is set.



              function getValue($key) {
              if (!isset($_GET[$key])) {
              return false;
              }
              return $_GET[$key];
              }

              if (getValue('myvar') == 'something') {
              // Do something
              }





              share|improve this answer


























              • Well I saw this around there, just hoping be possible without using arrays, thanks.

                – Mariz Melo
                Oct 24 '10 at 10:12











              • Updated my answer to show a possible way to do this without using another array.

                – mellowsoon
                Oct 24 '10 at 10:17











              • Thank you for the code Mellowsoon, back to work now.

                – Mariz Melo
                Oct 24 '10 at 10:35














              16












              16








              16







              Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:



              $required = array('myvar', 'foo', 'bar', 'baz');
              $missing = array_diff($required, array_keys($_GET));


              The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.



              Or you can use something like that:



              $required = array('myvar', 'foo', 'bar', 'baz');
              $missing = array_diff($required, array_keys($_GET));
              foreach($missing as $m ) {
              $_GET[$m] = null;
              }


              Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.



              Update



              One other way to clean up the code would be using a function that checks if the value is set.



              function getValue($key) {
              if (!isset($_GET[$key])) {
              return false;
              }
              return $_GET[$key];
              }

              if (getValue('myvar') == 'something') {
              // Do something
              }





              share|improve this answer















              Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:



              $required = array('myvar', 'foo', 'bar', 'baz');
              $missing = array_diff($required, array_keys($_GET));


              The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.



              Or you can use something like that:



              $required = array('myvar', 'foo', 'bar', 'baz');
              $missing = array_diff($required, array_keys($_GET));
              foreach($missing as $m ) {
              $_GET[$m] = null;
              }


              Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.



              Update



              One other way to clean up the code would be using a function that checks if the value is set.



              function getValue($key) {
              if (!isset($_GET[$key])) {
              return false;
              }
              return $_GET[$key];
              }

              if (getValue('myvar') == 'something') {
              // Do something
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 24 '10 at 10:17

























              answered Oct 24 '10 at 10:05









              mellowsoonmellowsoon

              7,810174670




              7,810174670













              • Well I saw this around there, just hoping be possible without using arrays, thanks.

                – Mariz Melo
                Oct 24 '10 at 10:12











              • Updated my answer to show a possible way to do this without using another array.

                – mellowsoon
                Oct 24 '10 at 10:17











              • Thank you for the code Mellowsoon, back to work now.

                – Mariz Melo
                Oct 24 '10 at 10:35



















              • Well I saw this around there, just hoping be possible without using arrays, thanks.

                – Mariz Melo
                Oct 24 '10 at 10:12











              • Updated my answer to show a possible way to do this without using another array.

                – mellowsoon
                Oct 24 '10 at 10:17











              • Thank you for the code Mellowsoon, back to work now.

                – Mariz Melo
                Oct 24 '10 at 10:35

















              Well I saw this around there, just hoping be possible without using arrays, thanks.

              – Mariz Melo
              Oct 24 '10 at 10:12





              Well I saw this around there, just hoping be possible without using arrays, thanks.

              – Mariz Melo
              Oct 24 '10 at 10:12













              Updated my answer to show a possible way to do this without using another array.

              – mellowsoon
              Oct 24 '10 at 10:17





              Updated my answer to show a possible way to do this without using another array.

              – mellowsoon
              Oct 24 '10 at 10:17













              Thank you for the code Mellowsoon, back to work now.

              – Mariz Melo
              Oct 24 '10 at 10:35





              Thank you for the code Mellowsoon, back to work now.

              – Mariz Melo
              Oct 24 '10 at 10:35













              8














              If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:



              if ((isset($variable) ? $variable : null) == $value) { }


              The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.






              share|improve this answer





















              • 4





                It is better to suggest === than ==, as it will not have the downside you mention.

                – trincot
                Aug 18 '16 at 17:38
















              8














              If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:



              if ((isset($variable) ? $variable : null) == $value) { }


              The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.






              share|improve this answer





















              • 4





                It is better to suggest === than ==, as it will not have the downside you mention.

                – trincot
                Aug 18 '16 at 17:38














              8












              8








              8







              If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:



              if ((isset($variable) ? $variable : null) == $value) { }


              The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.






              share|improve this answer















              If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:



              if ((isset($variable) ? $variable : null) == $value) { }


              The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 18 '16 at 17:37









              trincot

              119k1482115




              119k1482115










              answered Aug 18 '16 at 17:12









              James Hastings-TrewJames Hastings-Trew

              8111




              8111








              • 4





                It is better to suggest === than ==, as it will not have the downside you mention.

                – trincot
                Aug 18 '16 at 17:38














              • 4





                It is better to suggest === than ==, as it will not have the downside you mention.

                – trincot
                Aug 18 '16 at 17:38








              4




              4





              It is better to suggest === than ==, as it will not have the downside you mention.

              – trincot
              Aug 18 '16 at 17:38





              It is better to suggest === than ==, as it will not have the downside you mention.

              – trincot
              Aug 18 '16 at 17:38











              1














              As mellowsoon suggest, you might consider this approach:



              required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
              $missing = array_diff($required, array_keys($_GET));
              foreach($missing as $key => $default ) {
              $_GET[$key] = $default ;
              }


              You put the default values and set the not recieved parameters to a default value :)






              share|improve this answer




























                1














                As mellowsoon suggest, you might consider this approach:



                required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
                $missing = array_diff($required, array_keys($_GET));
                foreach($missing as $key => $default ) {
                $_GET[$key] = $default ;
                }


                You put the default values and set the not recieved parameters to a default value :)






                share|improve this answer


























                  1












                  1








                  1







                  As mellowsoon suggest, you might consider this approach:



                  required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
                  $missing = array_diff($required, array_keys($_GET));
                  foreach($missing as $key => $default ) {
                  $_GET[$key] = $default ;
                  }


                  You put the default values and set the not recieved parameters to a default value :)






                  share|improve this answer













                  As mellowsoon suggest, you might consider this approach:



                  required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
                  $missing = array_diff($required, array_keys($_GET));
                  foreach($missing as $key => $default ) {
                  $_GET[$key] = $default ;
                  }


                  You put the default values and set the not recieved parameters to a default value :)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 5 '11 at 13:36









                  VictorVictor

                  2,42822144




                  2,42822144























                      0















                      My question is, exist any way to do this without declare the variable twice?




                      No, there is no way to do this correctly without doing two checks. I hate it, too.



                      One way to work around it would be to import all relevant GET variables at one central point into an array or object of some sort (Most MVC frameworks do this automatically) and setting all properties that are needed later. (Instead of accessing request variables across the code.)






                      share|improve this answer


























                      • Just define all your variables. That's the point of all that mess.

                        – Your Common Sense
                        Oct 24 '10 at 10:05













                      • Thank you Pekka, is really very boring do that.

                        – Mariz Melo
                        Oct 24 '10 at 10:14











                      • Sometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.

                        – Mariz Melo
                        Oct 24 '10 at 10:15






                      • 2





                        @Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.

                        – Pekka 웃
                        Oct 24 '10 at 10:17













                      • Pekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.

                        – Mariz Melo
                        Oct 24 '10 at 10:31
















                      0















                      My question is, exist any way to do this without declare the variable twice?




                      No, there is no way to do this correctly without doing two checks. I hate it, too.



                      One way to work around it would be to import all relevant GET variables at one central point into an array or object of some sort (Most MVC frameworks do this automatically) and setting all properties that are needed later. (Instead of accessing request variables across the code.)






                      share|improve this answer


























                      • Just define all your variables. That's the point of all that mess.

                        – Your Common Sense
                        Oct 24 '10 at 10:05













                      • Thank you Pekka, is really very boring do that.

                        – Mariz Melo
                        Oct 24 '10 at 10:14











                      • Sometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.

                        – Mariz Melo
                        Oct 24 '10 at 10:15






                      • 2





                        @Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.

                        – Pekka 웃
                        Oct 24 '10 at 10:17













                      • Pekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.

                        – Mariz Melo
                        Oct 24 '10 at 10:31














                      0












                      0








                      0








                      My question is, exist any way to do this without declare the variable twice?




                      No, there is no way to do this correctly without doing two checks. I hate it, too.



                      One way to work around it would be to import all relevant GET variables at one central point into an array or object of some sort (Most MVC frameworks do this automatically) and setting all properties that are needed later. (Instead of accessing request variables across the code.)






                      share|improve this answer
















                      My question is, exist any way to do this without declare the variable twice?




                      No, there is no way to do this correctly without doing two checks. I hate it, too.



                      One way to work around it would be to import all relevant GET variables at one central point into an array or object of some sort (Most MVC frameworks do this automatically) and setting all properties that are needed later. (Instead of accessing request variables across the code.)







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 23 '17 at 12:02









                      Community

                      11




                      11










                      answered Oct 24 '10 at 10:02









                      Pekka 웃Pekka 웃

                      356k1168411012




                      356k1168411012













                      • Just define all your variables. That's the point of all that mess.

                        – Your Common Sense
                        Oct 24 '10 at 10:05













                      • Thank you Pekka, is really very boring do that.

                        – Mariz Melo
                        Oct 24 '10 at 10:14











                      • Sometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.

                        – Mariz Melo
                        Oct 24 '10 at 10:15






                      • 2





                        @Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.

                        – Pekka 웃
                        Oct 24 '10 at 10:17













                      • Pekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.

                        – Mariz Melo
                        Oct 24 '10 at 10:31



















                      • Just define all your variables. That's the point of all that mess.

                        – Your Common Sense
                        Oct 24 '10 at 10:05













                      • Thank you Pekka, is really very boring do that.

                        – Mariz Melo
                        Oct 24 '10 at 10:14











                      • Sometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.

                        – Mariz Melo
                        Oct 24 '10 at 10:15






                      • 2





                        @Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.

                        – Pekka 웃
                        Oct 24 '10 at 10:17













                      • Pekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.

                        – Mariz Melo
                        Oct 24 '10 at 10:31

















                      Just define all your variables. That's the point of all that mess.

                      – Your Common Sense
                      Oct 24 '10 at 10:05







                      Just define all your variables. That's the point of all that mess.

                      – Your Common Sense
                      Oct 24 '10 at 10:05















                      Thank you Pekka, is really very boring do that.

                      – Mariz Melo
                      Oct 24 '10 at 10:14





                      Thank you Pekka, is really very boring do that.

                      – Mariz Melo
                      Oct 24 '10 at 10:14













                      Sometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.

                      – Mariz Melo
                      Oct 24 '10 at 10:15





                      Sometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.

                      – Mariz Melo
                      Oct 24 '10 at 10:15




                      2




                      2





                      @Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.

                      – Pekka 웃
                      Oct 24 '10 at 10:17







                      @Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.

                      – Pekka 웃
                      Oct 24 '10 at 10:17















                      Pekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.

                      – Mariz Melo
                      Oct 24 '10 at 10:31





                      Pekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.

                      – Mariz Melo
                      Oct 24 '10 at 10:31











                      0














                      Thanks Mellowsoon and Pekka, I did some research here and come up with this:




                      • Check and declare each variable as null (if is the case) before start to use (as recommended):



                      !isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;


                      *ok this one is simple but works fine, you can start to use the variable everywhere after this line




                      • Using array to cover all cases:



                      $myvars = array( 'var1', 'var2', 'var3');
                      foreach($myvars as $key)
                      !isset($_GET[$key]) ? $_GET[$key] =0:0;


                      *after that you are free to use your variables (var1, var2, var3 ... etc),



                      PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);



                      ... Better approaches are welcome :)





                      UPDATE:



                      Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.




                      !isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;





                      share|improve this answer






























                        0














                        Thanks Mellowsoon and Pekka, I did some research here and come up with this:




                        • Check and declare each variable as null (if is the case) before start to use (as recommended):



                        !isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;


                        *ok this one is simple but works fine, you can start to use the variable everywhere after this line




                        • Using array to cover all cases:



                        $myvars = array( 'var1', 'var2', 'var3');
                        foreach($myvars as $key)
                        !isset($_GET[$key]) ? $_GET[$key] =0:0;


                        *after that you are free to use your variables (var1, var2, var3 ... etc),



                        PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);



                        ... Better approaches are welcome :)





                        UPDATE:



                        Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.




                        !isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;





                        share|improve this answer




























                          0












                          0








                          0







                          Thanks Mellowsoon and Pekka, I did some research here and come up with this:




                          • Check and declare each variable as null (if is the case) before start to use (as recommended):



                          !isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;


                          *ok this one is simple but works fine, you can start to use the variable everywhere after this line




                          • Using array to cover all cases:



                          $myvars = array( 'var1', 'var2', 'var3');
                          foreach($myvars as $key)
                          !isset($_GET[$key]) ? $_GET[$key] =0:0;


                          *after that you are free to use your variables (var1, var2, var3 ... etc),



                          PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);



                          ... Better approaches are welcome :)





                          UPDATE:



                          Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.




                          !isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;





                          share|improve this answer















                          Thanks Mellowsoon and Pekka, I did some research here and come up with this:




                          • Check and declare each variable as null (if is the case) before start to use (as recommended):



                          !isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;


                          *ok this one is simple but works fine, you can start to use the variable everywhere after this line




                          • Using array to cover all cases:



                          $myvars = array( 'var1', 'var2', 'var3');
                          foreach($myvars as $key)
                          !isset($_GET[$key]) ? $_GET[$key] =0:0;


                          *after that you are free to use your variables (var1, var2, var3 ... etc),



                          PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);



                          ... Better approaches are welcome :)





                          UPDATE:



                          Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.




                          !isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Oct 24 '10 at 21:33

























                          answered Oct 24 '10 at 21:24









                          Mariz MeloMariz Melo

                          3451917




                          3451917























                              0














                              why not create a function for doing this, convert the variable your want to check into a real variable, ex.



                              function _FX($name) { 
                              if (isset($$name)) return $$name;
                              else return null;
                              }


                              then you do _FX('param') == '123', just a thought






                              share|improve this answer


























                              • this will still fire an error notice when you call _FX('param')

                                – kmoney12
                                Sep 17 '16 at 3:21
















                              0














                              why not create a function for doing this, convert the variable your want to check into a real variable, ex.



                              function _FX($name) { 
                              if (isset($$name)) return $$name;
                              else return null;
                              }


                              then you do _FX('param') == '123', just a thought






                              share|improve this answer


























                              • this will still fire an error notice when you call _FX('param')

                                – kmoney12
                                Sep 17 '16 at 3:21














                              0












                              0








                              0







                              why not create a function for doing this, convert the variable your want to check into a real variable, ex.



                              function _FX($name) { 
                              if (isset($$name)) return $$name;
                              else return null;
                              }


                              then you do _FX('param') == '123', just a thought






                              share|improve this answer















                              why not create a function for doing this, convert the variable your want to check into a real variable, ex.



                              function _FX($name) { 
                              if (isset($$name)) return $$name;
                              else return null;
                              }


                              then you do _FX('param') == '123', just a thought







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 15 '12 at 11:01









                              blasteralfred Ψ

                              12.6k46137206




                              12.6k46137206










                              answered Aug 24 '11 at 1:29









                              windmaomaowindmaomao

                              1,2131213




                              1,2131213













                              • this will still fire an error notice when you call _FX('param')

                                – kmoney12
                                Sep 17 '16 at 3:21



















                              • this will still fire an error notice when you call _FX('param')

                                – kmoney12
                                Sep 17 '16 at 3:21

















                              this will still fire an error notice when you call _FX('param')

                              – kmoney12
                              Sep 17 '16 at 3:21





                              this will still fire an error notice when you call _FX('param')

                              – kmoney12
                              Sep 17 '16 at 3:21











                              0














                              I use all time own useful function exst() which automatically declare variables.



                              Example -



                              $element1 = exst($arr["key1"]);
                              $val2 = exst($_POST["key2"], 'novalue');


                              /**
                              * Function exst() - Checks if the variable has been set
                              * (copy/paste it in any place of your code)
                              *
                              * If the variable is set and not empty returns the variable (no transformation)
                              * If the variable is not set or empty, returns the $default value
                              *
                              * @param mixed $var
                              * @param mixed $default
                              *
                              * @return mixed
                              */

                              function exst( & $var, $default = "")
                              {
                              $t = "";
                              if ( !isset($var) || !$var ) {
                              if (isset($default) && $default != "") $t = $default;
                              }
                              else {
                              $t = $var;
                              }
                              if (is_string($t)) $t = trim($t);
                              return $t;
                              }





                              share|improve this answer
























                              • Unfortunately this triggers a PHP notice if the array key doesn't exist, does it not?

                                – Matt Browne
                                Aug 10 '13 at 5:24
















                              0














                              I use all time own useful function exst() which automatically declare variables.



                              Example -



                              $element1 = exst($arr["key1"]);
                              $val2 = exst($_POST["key2"], 'novalue');


                              /**
                              * Function exst() - Checks if the variable has been set
                              * (copy/paste it in any place of your code)
                              *
                              * If the variable is set and not empty returns the variable (no transformation)
                              * If the variable is not set or empty, returns the $default value
                              *
                              * @param mixed $var
                              * @param mixed $default
                              *
                              * @return mixed
                              */

                              function exst( & $var, $default = "")
                              {
                              $t = "";
                              if ( !isset($var) || !$var ) {
                              if (isset($default) && $default != "") $t = $default;
                              }
                              else {
                              $t = $var;
                              }
                              if (is_string($t)) $t = trim($t);
                              return $t;
                              }





                              share|improve this answer
























                              • Unfortunately this triggers a PHP notice if the array key doesn't exist, does it not?

                                – Matt Browne
                                Aug 10 '13 at 5:24














                              0












                              0








                              0







                              I use all time own useful function exst() which automatically declare variables.



                              Example -



                              $element1 = exst($arr["key1"]);
                              $val2 = exst($_POST["key2"], 'novalue');


                              /**
                              * Function exst() - Checks if the variable has been set
                              * (copy/paste it in any place of your code)
                              *
                              * If the variable is set and not empty returns the variable (no transformation)
                              * If the variable is not set or empty, returns the $default value
                              *
                              * @param mixed $var
                              * @param mixed $default
                              *
                              * @return mixed
                              */

                              function exst( & $var, $default = "")
                              {
                              $t = "";
                              if ( !isset($var) || !$var ) {
                              if (isset($default) && $default != "") $t = $default;
                              }
                              else {
                              $t = $var;
                              }
                              if (is_string($t)) $t = trim($t);
                              return $t;
                              }





                              share|improve this answer













                              I use all time own useful function exst() which automatically declare variables.



                              Example -



                              $element1 = exst($arr["key1"]);
                              $val2 = exst($_POST["key2"], 'novalue');


                              /**
                              * Function exst() - Checks if the variable has been set
                              * (copy/paste it in any place of your code)
                              *
                              * If the variable is set and not empty returns the variable (no transformation)
                              * If the variable is not set or empty, returns the $default value
                              *
                              * @param mixed $var
                              * @param mixed $default
                              *
                              * @return mixed
                              */

                              function exst( & $var, $default = "")
                              {
                              $t = "";
                              if ( !isset($var) || !$var ) {
                              if (isset($default) && $default != "") $t = $default;
                              }
                              else {
                              $t = $var;
                              }
                              if (is_string($t)) $t = trim($t);
                              return $t;
                              }






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Apr 10 '13 at 12:01









                              user2253362user2253362

                              6113




                              6113













                              • Unfortunately this triggers a PHP notice if the array key doesn't exist, does it not?

                                – Matt Browne
                                Aug 10 '13 at 5:24



















                              • Unfortunately this triggers a PHP notice if the array key doesn't exist, does it not?

                                – Matt Browne
                                Aug 10 '13 at 5:24

















                              Unfortunately this triggers a PHP notice if the array key doesn't exist, does it not?

                              – Matt Browne
                              Aug 10 '13 at 5:24





                              Unfortunately this triggers a PHP notice if the array key doesn't exist, does it not?

                              – Matt Browne
                              Aug 10 '13 at 5:24











                              0














                              A solution that I have found from playing around is to do:



                              if($x=&$_GET["myvar"] == "something")
                              {
                              // do stuff with $x
                              }





                              share|improve this answer




























                                0














                                A solution that I have found from playing around is to do:



                                if($x=&$_GET["myvar"] == "something")
                                {
                                // do stuff with $x
                                }





                                share|improve this answer


























                                  0












                                  0








                                  0







                                  A solution that I have found from playing around is to do:



                                  if($x=&$_GET["myvar"] == "something")
                                  {
                                  // do stuff with $x
                                  }





                                  share|improve this answer













                                  A solution that I have found from playing around is to do:



                                  if($x=&$_GET["myvar"] == "something")
                                  {
                                  // do stuff with $x
                                  }






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Dec 14 '13 at 1:36









                                  Sheldon JunckerSheldon Juncker

                                  3121417




                                  3121417























                                      0














                                      <?php

                                      function myset(&$var,$value=false){
                                      if(isset($var)):
                                      return $var == $value ? $value : false;
                                      endif;
                                      return false;
                                      }

                                      $array['key'] = 'foo';

                                      var_dump(myset($array['key'],'bar')); //bool(false)

                                      var_dump(myset($array['key'],'foo'));//string(3) "foo"

                                      var_dump(myset($array['baz'],'bar'));//bool(false)





                                      share|improve this answer






























                                        0














                                        <?php

                                        function myset(&$var,$value=false){
                                        if(isset($var)):
                                        return $var == $value ? $value : false;
                                        endif;
                                        return false;
                                        }

                                        $array['key'] = 'foo';

                                        var_dump(myset($array['key'],'bar')); //bool(false)

                                        var_dump(myset($array['key'],'foo'));//string(3) "foo"

                                        var_dump(myset($array['baz'],'bar'));//bool(false)





                                        share|improve this answer




























                                          0












                                          0








                                          0







                                          <?php

                                          function myset(&$var,$value=false){
                                          if(isset($var)):
                                          return $var == $value ? $value : false;
                                          endif;
                                          return false;
                                          }

                                          $array['key'] = 'foo';

                                          var_dump(myset($array['key'],'bar')); //bool(false)

                                          var_dump(myset($array['key'],'foo'));//string(3) "foo"

                                          var_dump(myset($array['baz'],'bar'));//bool(false)





                                          share|improve this answer















                                          <?php

                                          function myset(&$var,$value=false){
                                          if(isset($var)):
                                          return $var == $value ? $value : false;
                                          endif;
                                          return false;
                                          }

                                          $array['key'] = 'foo';

                                          var_dump(myset($array['key'],'bar')); //bool(false)

                                          var_dump(myset($array['key'],'foo'));//string(3) "foo"

                                          var_dump(myset($array['baz'],'bar'));//bool(false)






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Mar 14 '14 at 14:34

























                                          answered Mar 14 '14 at 14:24









                                          keithicskeithics

                                          6,24823631




                                          6,24823631























                                              0














                                              This is similar to the accepted answer, but uses in_array instead. I prefer to use empty() in this situation. I also suggest using the new shorthand array declaration which is available in PHP 5.4.0+.



                                              $allowed = ["something","nothing"];
                                              if(!empty($_GET['myvar']) && in_array($_GET['myvar'],$allowed)){..}


                                              Here is a function for checking multiple values at once.



                                              $arrKeys = array_keys($_GET);
                                              $allowed = ["something","nothing"];

                                              function checkGet($arrKeys,$allowed) {
                                              foreach($arrKeys as $key ) {
                                              if(in_array($_GET[$key],$allowed)) {
                                              $values[$key];
                                              }
                                              }
                                              return $values;
                                              }





                                              share|improve this answer






























                                                0














                                                This is similar to the accepted answer, but uses in_array instead. I prefer to use empty() in this situation. I also suggest using the new shorthand array declaration which is available in PHP 5.4.0+.



                                                $allowed = ["something","nothing"];
                                                if(!empty($_GET['myvar']) && in_array($_GET['myvar'],$allowed)){..}


                                                Here is a function for checking multiple values at once.



                                                $arrKeys = array_keys($_GET);
                                                $allowed = ["something","nothing"];

                                                function checkGet($arrKeys,$allowed) {
                                                foreach($arrKeys as $key ) {
                                                if(in_array($_GET[$key],$allowed)) {
                                                $values[$key];
                                                }
                                                }
                                                return $values;
                                                }





                                                share|improve this answer




























                                                  0












                                                  0








                                                  0







                                                  This is similar to the accepted answer, but uses in_array instead. I prefer to use empty() in this situation. I also suggest using the new shorthand array declaration which is available in PHP 5.4.0+.



                                                  $allowed = ["something","nothing"];
                                                  if(!empty($_GET['myvar']) && in_array($_GET['myvar'],$allowed)){..}


                                                  Here is a function for checking multiple values at once.



                                                  $arrKeys = array_keys($_GET);
                                                  $allowed = ["something","nothing"];

                                                  function checkGet($arrKeys,$allowed) {
                                                  foreach($arrKeys as $key ) {
                                                  if(in_array($_GET[$key],$allowed)) {
                                                  $values[$key];
                                                  }
                                                  }
                                                  return $values;
                                                  }





                                                  share|improve this answer















                                                  This is similar to the accepted answer, but uses in_array instead. I prefer to use empty() in this situation. I also suggest using the new shorthand array declaration which is available in PHP 5.4.0+.



                                                  $allowed = ["something","nothing"];
                                                  if(!empty($_GET['myvar']) && in_array($_GET['myvar'],$allowed)){..}


                                                  Here is a function for checking multiple values at once.



                                                  $arrKeys = array_keys($_GET);
                                                  $allowed = ["something","nothing"];

                                                  function checkGet($arrKeys,$allowed) {
                                                  foreach($arrKeys as $key ) {
                                                  if(in_array($_GET[$key],$allowed)) {
                                                  $values[$key];
                                                  }
                                                  }
                                                  return $values;
                                                  }






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Nov 11 '14 at 20:56

























                                                  answered Nov 11 '14 at 11:40









                                                  EternalHourEternalHour

                                                  4,98062648




                                                  4,98062648























                                                      0














                                                      As of PHP7 you can use the Null Coalescing Operator ?? to avoid the double reference:



                                                      $_GET['myvar'] = 'hello';
                                                      if (($_GET['myvar'] ?? '') == 'hello') {
                                                      echo "hello!";
                                                      }


                                                      Output:



                                                      hello!


                                                      In general, the expression



                                                      $a ?? $b


                                                      is equivalent to



                                                      isset($a) ? $a : $b





                                                      share|improve this answer






























                                                        0














                                                        As of PHP7 you can use the Null Coalescing Operator ?? to avoid the double reference:



                                                        $_GET['myvar'] = 'hello';
                                                        if (($_GET['myvar'] ?? '') == 'hello') {
                                                        echo "hello!";
                                                        }


                                                        Output:



                                                        hello!


                                                        In general, the expression



                                                        $a ?? $b


                                                        is equivalent to



                                                        isset($a) ? $a : $b





                                                        share|improve this answer




























                                                          0












                                                          0








                                                          0







                                                          As of PHP7 you can use the Null Coalescing Operator ?? to avoid the double reference:



                                                          $_GET['myvar'] = 'hello';
                                                          if (($_GET['myvar'] ?? '') == 'hello') {
                                                          echo "hello!";
                                                          }


                                                          Output:



                                                          hello!


                                                          In general, the expression



                                                          $a ?? $b


                                                          is equivalent to



                                                          isset($a) ? $a : $b





                                                          share|improve this answer















                                                          As of PHP7 you can use the Null Coalescing Operator ?? to avoid the double reference:



                                                          $_GET['myvar'] = 'hello';
                                                          if (($_GET['myvar'] ?? '') == 'hello') {
                                                          echo "hello!";
                                                          }


                                                          Output:



                                                          hello!


                                                          In general, the expression



                                                          $a ?? $b


                                                          is equivalent to



                                                          isset($a) ? $a : $b






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Nov 24 '18 at 6:29

























                                                          answered Nov 24 '18 at 4:57









                                                          NickNick

                                                          25.1k91735




                                                          25.1k91735























                                                              -1














                                                              Well, you could get by with just if($_GET['myvar'] == 'something') since that condition presumes that the variable also exists. If it doesn't, the expression will also result in false.



                                                              I think it's ok to do this inside conditional statements like above. No harm done really.






                                                              share|improve this answer


























                                                              • And it fires a notice, if the myvar index doesn't exist.

                                                                – erenon
                                                                Oct 24 '10 at 12:30






                                                              • 1





                                                                True, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).

                                                                – DanMan
                                                                Oct 24 '10 at 12:35








                                                              • 1





                                                                Oof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.

                                                                – Ross Snyder
                                                                Oct 24 '10 at 21:38
















                                                              -1














                                                              Well, you could get by with just if($_GET['myvar'] == 'something') since that condition presumes that the variable also exists. If it doesn't, the expression will also result in false.



                                                              I think it's ok to do this inside conditional statements like above. No harm done really.






                                                              share|improve this answer


























                                                              • And it fires a notice, if the myvar index doesn't exist.

                                                                – erenon
                                                                Oct 24 '10 at 12:30






                                                              • 1





                                                                True, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).

                                                                – DanMan
                                                                Oct 24 '10 at 12:35








                                                              • 1





                                                                Oof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.

                                                                – Ross Snyder
                                                                Oct 24 '10 at 21:38














                                                              -1












                                                              -1








                                                              -1







                                                              Well, you could get by with just if($_GET['myvar'] == 'something') since that condition presumes that the variable also exists. If it doesn't, the expression will also result in false.



                                                              I think it's ok to do this inside conditional statements like above. No harm done really.






                                                              share|improve this answer















                                                              Well, you could get by with just if($_GET['myvar'] == 'something') since that condition presumes that the variable also exists. If it doesn't, the expression will also result in false.



                                                              I think it's ok to do this inside conditional statements like above. No harm done really.







                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Oct 24 '10 at 12:33

























                                                              answered Oct 24 '10 at 12:28









                                                              DanManDanMan

                                                              8,42632954




                                                              8,42632954













                                                              • And it fires a notice, if the myvar index doesn't exist.

                                                                – erenon
                                                                Oct 24 '10 at 12:30






                                                              • 1





                                                                True, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).

                                                                – DanMan
                                                                Oct 24 '10 at 12:35








                                                              • 1





                                                                Oof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.

                                                                – Ross Snyder
                                                                Oct 24 '10 at 21:38



















                                                              • And it fires a notice, if the myvar index doesn't exist.

                                                                – erenon
                                                                Oct 24 '10 at 12:30






                                                              • 1





                                                                True, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).

                                                                – DanMan
                                                                Oct 24 '10 at 12:35








                                                              • 1





                                                                Oof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.

                                                                – Ross Snyder
                                                                Oct 24 '10 at 21:38

















                                                              And it fires a notice, if the myvar index doesn't exist.

                                                              – erenon
                                                              Oct 24 '10 at 12:30





                                                              And it fires a notice, if the myvar index doesn't exist.

                                                              – erenon
                                                              Oct 24 '10 at 12:30




                                                              1




                                                              1





                                                              True, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).

                                                              – DanMan
                                                              Oct 24 '10 at 12:35







                                                              True, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).

                                                              – DanMan
                                                              Oct 24 '10 at 12:35






                                                              1




                                                              1





                                                              Oof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.

                                                              – Ross Snyder
                                                              Oct 24 '10 at 21:38





                                                              Oof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.

                                                              – Ross Snyder
                                                              Oct 24 '10 at 21:38











                                                              -3














                                                              No official reference but it worked when I tried this:



                                                              if (isset($_GET['myvar']) == 'something')





                                                              share|improve this answer



















                                                              • 1





                                                                Nope. This is comparing TRUE/FALSE against 'something'.

                                                                – Dan H
                                                                Sep 8 '14 at 11:25
















                                                              -3














                                                              No official reference but it worked when I tried this:



                                                              if (isset($_GET['myvar']) == 'something')





                                                              share|improve this answer



















                                                              • 1





                                                                Nope. This is comparing TRUE/FALSE against 'something'.

                                                                – Dan H
                                                                Sep 8 '14 at 11:25














                                                              -3












                                                              -3








                                                              -3







                                                              No official reference but it worked when I tried this:



                                                              if (isset($_GET['myvar']) == 'something')





                                                              share|improve this answer













                                                              No official reference but it worked when I tried this:



                                                              if (isset($_GET['myvar']) == 'something')






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Mar 4 '14 at 21:40









                                                              zaferzafer

                                                              1




                                                              1








                                                              • 1





                                                                Nope. This is comparing TRUE/FALSE against 'something'.

                                                                – Dan H
                                                                Sep 8 '14 at 11:25














                                                              • 1





                                                                Nope. This is comparing TRUE/FALSE against 'something'.

                                                                – Dan H
                                                                Sep 8 '14 at 11:25








                                                              1




                                                              1





                                                              Nope. This is comparing TRUE/FALSE against 'something'.

                                                              – Dan H
                                                              Sep 8 '14 at 11:25





                                                              Nope. This is comparing TRUE/FALSE against 'something'.

                                                              – Dan H
                                                              Sep 8 '14 at 11:25


















                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4007752%2fphp-check-if-variable-exist-but-also-if-has-a-value-equal-to-something%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                                                              Calculate evaluation metrics using cross_val_predict sklearn

                                                              Insert data from modal to MySQL (multiple modal on website)