Search code examples
phpvariablesisset

Efficient way to check multiple variables declarations?


In a project of mine I am working with a sequence of pages that each give information that is used in the next, with POST and session variables. Simple example:

Page 1: enter name -> page 2 display name; ask birth date -> page 3 display name and birth date.

If a user goes directly to page 3 I want to display a message that s/he has not entered a name and/or birth date and should try again. Currently I am still doing it like so. On page 2:

if (isset($_POST['name'])) $_SESSION['name'] = $_POST['name'];

and page 3:

if (isset($_SESSION['name'])) $name = $_SESSION['name'];
if (isset($_POST['bday'])) $_SESSION['bday'] = $_POST['bday'];

as declarations and in the body an if-clause like

if (isset($name) && isset($_SESSION['bday'])) {
    // do main stuff
else {
    // display error message
}

The example is simple enough, but in the real world my code has a lot more variables and data from the forms, and putting all this first in variable assignments and then in an if-clause is tiring and seems not efficient to me. Is there a better, more straightforward way to check things like this? Or is what I posted the best, most-used way to go?


Solution

  • You can use one call to isset to check several variables.

    isset($_SESSION['name'], $_SESSION['bday'], ...)
    

    Or you can write your own function like

    if (variablesFilled(['name', 'bday', ...])) { }
    
    function variablesFilled($array) {
       foreach ($array as $entry) {
         if (!isset($_SESSION[$entry])) {
           return false;
         }
       }
       return true;
    }