Reputation: 6042
I'm trying to replace empty field values with NULL, but can't seem to figure out how to do it. I've tried array_map
, array_filter
, and array_walk
, but to no avail. Example:
function replaceWithNull($var)
{
if (empty($var) || $var == ' ') {
$var = "NULL";
}
}
array_walk($_POST, "replaceWithNull");
Instead, it remains empty/blank. What am I missing?
Upvotes: 2
Views: 1164
Reputation: 6036
hey guys look this code:
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!';
}
?>
Upvotes: -2
Reputation: 12283
You have to use references for argument passing in order to alter the elements in the array:
function replaceWithNull(&$var)
{
...
}
Otherwise you will be changing only a copy of the variable.
Read about it here: http://www.php.net/manual/en/functions.arguments.php
Upvotes: 6
Reputation:
You're only modifying the local copy of the variable. You must pass the value by reference to modify the value in the actual array:
function replaceWithNull(&$var)
{
if (empty($var) || $var == ' ') {
$var = "NULL";
}
}
Upvotes: 5