在$ _POST中用NULL替换空值

时间:2011-12-27 16:18:58

标签: php arrays

我正在尝试用NULL替换空字段值,但似乎无法弄清楚如何做到这一点。我尝试了array_maparray_filterarray_walk,但无济于事。例如:

function replaceWithNull($var)
{
    if (empty($var) || $var == ' ') {
        $var = "NULL";
    }
}

array_walk($_POST, "replaceWithNull");

相反,它仍为空/空白。我错过了什么?

3 个答案:

答案 0 :(得分:6)

您必须使用引用传递参数才能更改数组中的元素:

function replaceWithNull(&$var)
{
    ...
}

否则您只会更改变量的副本。

在此处阅读:http://www.php.net/manual/en/functions.arguments.php

答案 1 :(得分:5)

您只修改变量的本地副本。您必须pass the value by reference来修改实际数组中的值:

function replaceWithNull(&$var)
{
    if (empty($var) || $var == ' ') {
        $var = "NULL";
    }
}

答案 2 :(得分:-2)

嘿伙计们看这段代码:

<强>的config.php

<?php
if( is_array( $_POST ) and count( $_POST ) > 0 )
{
    foreach( $_POST as $key => $value )
    {

        if( is_array( $value ) )
        {
            foreach( $value as $k => $val )
            {
                if( is_string( $val ) )
                {
                    if( empty($val) OR strlen(preg_replace("/(\s+)?/", $val)) == 0 )
                    {
                        $_POST[$key][$k] = null;
                    }
                }
            }
        }else{
            if( empty($value) OR strlen(preg_replace("/(\s+)?/", $value)) == 0 )
            {
                $_POST[$key] = null;
            }
        }


    }
}
?>

<强> TEST:

<?php
var_dump( $_POST );
exit;
?>

<强> myApp.php

<?php
include( 'config.php');
//.... your code here....
if(is_null( $_POST['firstname'] ))
{
    echo 'hey men! error!';
}
?>