如果在数组中没有找到消息,那么它也返回2而不是null PHP

时间:2012-02-13 15:09:57

标签: php

如果在数组中没有找到消息,那么它返回2而不是null PHP

我将消息附加到数组并调用函数来追加数组但是在调用函数时没有在数组中找到消息,它也将它们显示为2值,这些是Array([0] => [1] =&gt ;)

$errorMessages = array ();

    $isError = false;
    $middleName = $_POST [ 'middleName' ];
    $middleName = trim( stripslashes( $middleName ) );

    //validation for warrant id
    $warrantId = $_POST [ 'warrantId' ];
    if ( $warrantId == null || ( strlen( $warrantId ) ) <= 0 ) {
        $errorMessages[] = "Warrant Id is required";
    }  else {
        $message = 'enter keyboard characters only for warrant Id.';
        $warrantId = trim( stripslashes( $warrantId ) );
        $x = checkLength($warrantId, 'WarrantId', 1);
        $errorMessages[] = $x;

        //$errorMessages[] = checkRegEx( $warrantId, '/^([a-zA-Z0-9._\- #,^&`~<>:!@$(){}\"\';\*\[\]?%| \n \r \t]*)$/', $message );
    }

    $errorMsg = count($errorMessages);
    print_r($errorMsg);

功能

/*
* Checks the field length is not greater than allowed length
* @params unknown values $fieldValue, $fieldName, $maxLength
* @return tables rows $rowResponse
*/
function checkLength($fieldValue, $fieldName, $maxLength) { 
    $errorMsg = NULL;
if (strlen ( $fieldValue ) > $maxLength) {

    $errorMsg = $fieldName . " cannot be greater than " . $maxLength . " characters.";
}   
return $errorMsg;   
}

/*
* Checks the given field value to match with regular expression or not
* @params unknown values $fieldValue, $mask, $message
* @return tables rows $rowResponse
*/
function checkRegEx($fieldValue, $regEx, $message) {
    $errorMsg = NULL;
if (! (preg_match ( $regEx, $fieldValue ))) {
    $errorMsg =  $message;
}

return $errorMsg;   
}

如果在数组中没有找到消息,那么它也将它返回为2

1 个答案:

答案 0 :(得分:2)

checkLengthcheckRegEx函数返回NULL并将其添加到数组中。如果函数调用的结果不返回NULL,则只应分配函数调用的结果。

$x = checkLength($warrantId, 'WarrantId', 1);
if ($x !== NULL) {
    $errorMessages[] = $x;
}

$x = checkRegEx( $warrantId, '/^([a-zA-Z0-9._\- #,^&`~<>:!@$(){}\"\';\*\[\]?%| \n \r \t]*)$/', $message );
if ($x !== NULL) {
    $errorMessages[] = $x;
}