开发者

PHP empty($val) function returns true if value is set to 0

I have the following PHP code:

$required_fields = array ('menu_name','visible','position');
foreach($required_fields as $fieldname)
{
    if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname]) )
    {
        $errors [] = $fieldname;
    }
}

menu_name, visible and position are variables that are received through the post method.

When the value of visible is ze开发者_如何学Pythonro, it creates an entry into the error array.

What is the best way to detect if a variable is empty when 0 is considered "not empty"?


From PHP's manual:

empty() returns FALSE if var has a non-empty and non-zero value.

Do something like this:

if ( !IsSet ( $_POST['field'] ) || Trim ( $_POST['field'] ) == '' )

this will ensure that the field is set and that it does not contain a empty string

In essence: it is the empty() that is causing your problems not IsSet()


Since user data is sloppy, I use a custom function that treats empty spaces as non data. It sounds like this will do exactly what you want. This function will consider "0" to be valid (aka non-empty) data.

function isNullOrEmpty( $arg )
{
    if ( !is_array( $arg ) )
    {
        $arg = array( $arg );
    }

    foreach ( $arg as $key => $value )
    {
        $value = trim($value);
        if( $value == "" || $value == null )
        {
            return true;
        }
    }
    return false;
}

Please note it supports arrays too but requires that each value in the array contains data, which can be useful as you can just do something like this:

$required = array( $_POST['name'],  $_POST['age'], $_POST['weight'] );
if ( isNullOrEmpty($required) )
{
  // required data is missing
}

PS: keep in mind this function will fire off PHP warnings if the value isn't set and there's no easy way around that, but you should NOT have warnings enabled in production anyways.


If you want to assure an array key is present you can use array_key_exists() instead of empty()

The check will become a concatenation of is_array() and array_key_exists(), being paranoid of course


Can't you just add another line with something like:

if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname]) )
{
    if ($fieldname != 'visible' || $_POST[$fieldname] != 0)
    { 
        $errors [] = $fieldname;
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜