检查array_values是否为null

时间:2016-01-17 21:15:54

标签: php arrays

如果没有错误,尝试提交表单,问题是错误数组的状态,空,空或未设置。这些检查都没有奏效。

我确信有更好的方法来获取/收集错误消息并检查数组,非常欢迎任何建议。

$validate = array();

    if (isset($_POST['submit'])) {

$validate[] = $user->inputLessThan($user->username, 8);
$validate[] = $user->emptyInput($user->firstName);
$validate[] = $user->emptyInput($user->lastName);
$validate[] = $user->emptyInput($user->email);
$validate[] = $user->validEmail($user->email);
$validate[] = $user->emailExists($user->email);
$validate[] = $user->emptyInput($user->phoneCell);
$validate[] = $user->validatePassword($user->password,$_POST['passwordConfirm']);



/* var_dump($validate); 
 * if all fields were filled properly returns all NULL. "no errors!"
 * array(8) { [0]=> NULL [1]=> NULL [2]=> NULL [3]=> NULL [4]=> NULL [5]=> NULL [6]=> NULL [7]=> NULL }
 */


// try submitting the form if no errors stored in $validate && insert-to-db     
// if(!isset($validate)) {  
// if(is_null($validate)) {     
// if(empty($validate)) {
// if(array_values($validate) == NULL) {
// if(is_array($validate) && empty($validate)) {
// NONE of the above worked.

if(is_array($validate) && empty($validate)) {

            $hashedPassword = $user->hashPassword($user->password);
            $activationCode = $user->getActivationCode();

        if(is_array($userData)) {

            $userData['username']   = $user->username;
            $userData['firstName']  = $user->firstName;
            $userData['lastName']   = $user->lastName;
            $userData['email']      = $user->email;
            $userData['address']    = $user->address;
            $userData['country']    = $user->country;
            $userData['phoneCell']  = $user->phoneCell;
            $userData['password']   = $hashedPassword;
            $userData['active']     = $activationCode;

            }

            /* var_dump($userData); 
             * 
             * displays the array if checked with isset($validate) for debuging
             * 
             * 
             * ["username"]=> string(12) "userName@1.com" 
             * ["firstName"]=> string(12) "userName@1.com" 
             * etc.... }
             * registerUser method insters to db.
             */

            $user->registerUser($userData);

    }

/* loop to display errors, works.
*       if(isset($validate)){
*       foreach($validate as $error){
*           echo '<p class="bg-danger">'.$error.'</p>';
*               }
*           }
* class methods are functioning. e.g.
*
*
*   public function emptyInput($input) {
*       if(empty($input)) {
*       return $error = "field cannot be empty.";
*           }
*       }       
*
* used as above $validate[] = $user->emptyInput($user->firstName);
* to add the method return message to the array $validate.
*
*/

1 个答案:

答案 0 :(得分:0)

尝试清空(array_filter($ validate))

http://php.net/manual/en/function.array-filter.php

如果你的PHP版本是&lt; 5.5然后分成两个:

$validate = array_filter($validate);
if ( empty($validate) )
{

}