I use Codeigniter as the framework and create an array like below using input parameters from a form.
$data = array(
'generated_id' => $this->input->post('generated_id'),
'one' => $this->input->post('one'),
'two' => $this->input->post('two'),
'three' => $this->input->post('three'),
'modified_date' => date('Y-m-d H:i:s'),
'modified_user_id' => $this->session->userdata('user_id')
);
What I want to do is if the value from the input fields are empty I want to set the value of the particular array position to NULL. I'm using below function to get it done.
$data = array_filter($data,function($value, $key){
if(empty($value))
return NULL;
else
return $value;
}, ARRAY_FILTER_USE_BOTH);
But I end up with below error.
Use of undefined constant ARRAY_FILTER_USE_BOTH - assumed 'ARRAY_FILTER_USE_BOTH'
Is there an easy way to get this done or how can I fix this?
Since you're not using $key
in your callback at all, you do not need the ARRAY_FILTER_USE_BOTH
flag either. Your function can be simplified to:
$data = array_filter($data);
Seriously, it does the same thing.
What I want to do is if the value from the input fields are empty I want to set the value of the particular array position to
NULL
.
array_filter
won't do that to begin with. It will completely remove "empty" elements, not set them to null
. You want:
$data = array_map(function ($value) { return $value ?: null; }, $data);
This will set any values which are falsey (empty strings, 0
, empty arrays) to null
.