Search code examples
phparraysassociative-arrayconventionsternary-operator

Least verbose way of defining a default array value


Is there a cleaner way to check for array values to prevent PHP notices? Currently I do this:

$email      = (isset($_POST['user_email']))      ? $_POST['user_email']      : '';
$first_name = (isset($_POST['user_first_name'])) ? $_POST['user_first_name'] : '';
$last_name  = (isset($_POST['user_last_name']))  ? $_POST['user_last_namel'] : '';
$birthday   = (isset($_POST['user_last_name']))  ? $_POST['user_last_namel'] : '';

Is there a way to do something like JavaScript where you just provide a default, like this?

user.email = response.email || '';

I don't want to suppress notices, but these ugly checks clutter up my code. I'm on PHP 5.2.6.


Solution

  • You can create a function:

    $email      = getPost('user_email');
    $first_name = getPost('user_first_name');
    $last_name  = getPost('user_last_name');
    $birthday   = getPost('user_birthday');
    
    
    function getPost($key, $default = '')
    {
        if (isset($_POST[$key])) {
            return $_POST[$key];
        }
        return $default;
    }
    

    Putting it in a function also let's you do additional sanitizing more easily, e.g., trim(), if desired.

    You can also pass a default value that will be returned:

    $flavor = getPost('flavor', 'vanilla'); // if $_POST['flavor'] is not set, 'vanilla' is returned