Search code examples
phpfor-looppostisset

Easiest way to check if multiple POST parameters are set?


Hi so I want to know the easiest way to check if multiple POST parameters are set. Instead of doing a long if check with multiple "isset($_POST['example'])" linked together by "&&", I wanted to know if there was a cleaner way of doing it.

What I ended up doing was making an array and looping over it:

  $params_needed = ["song_name", "artist_name", "song_release_date",
                "song_genre", "song_medium"];

I would then call the function below, passing in $params_needed to check if the parameter names above are set:

  function all_params_valid($params_needed) {
     foreach ($params_needed as $param) {
        if (!isset($_POST[$param])) {
           error("Missing the " . $param . " variable in POST request.");
           return false;
        }
     }
     return true;
  }


  if (all_params_valid($params_needed)) {
     $song_name = $_POST["song_name"];
     $artist_name = $_POST["artist_name"];
     $song_release_date = $_POST["song_release_date"];
     $song_genre = $_POST["song_genre"];
     $song_medium = $_POST["song_medium"];

     ...
  }

However when I do this, it gets stuck on the first index and says "Missing the song_name variable..." despite actually including it in the POST request, and I'm not sure why this is happening. The expected behavior would be for it to move on and tell me the next parameter "artist_name" is not set, but this doesn't happen.


Solution

  • I personally like using array_diff for this issue.

    PHP array_diff documentation

    What you care about is your expected input is the same as the given input.

    So you can use array_diff like this:

      $params_needed = ["song_name", "artist_name", "song_release_date",
                    "song_genre", "song_medium"];
      $given_params = array_keys($_POST);
    
      $missing_params = array_diff($params_needed, $given_params);
    
      if(!empty($missing_params)) {
        // uh oh, someone didn't complete the form completely...
      }