Last Updated: February 25, 2016
·
976
· morrelinko

[PHP] Easier way to check if form keys exists

This function makes sure that form keys exists before processing.
And also avoids codes such as

$username = isset($POST['username']) ? $POST['username'] : null;
$password = isset($POST['password']) ? $POST['password'] : null;

Usage:

if(form_has_keys($_POST, array('username', 'password')))
{
    // submit data  
}
else
{
    // echo 'Invalid Form Data';    
}

// Function
    function form_has_keys($aPost, $aKeys = array())
    {
        $iFailed = 0;

        foreach($aKeys as $sKey)
        {
            if(!array_key_exists($sKey, $aPost))
            {
                $iFailed++; 
            }
        }

        return $iFailed > 0 ? false : true;
    }