Justin Kelly

various ramblings

PHP: Strip Null Entries From an Array : How To

For a while i’ve had issues with certain db update queries in php - particularly where image uploads are involved

My original code looked like

but using the above code would over write the image fields in the db if the user didn’t upload a new image

to get around this problem i wrote a is_null check on the image fields and pretty much write the $data array twice - once with the image fields and once without
- as i couldn’t put php code in the middle of the array
- this is a pretty crappy solution so i sat down and figured out a simple way to strip null entries from an array - see code below

now i don’t need to write the $data array twice - i can just use

$this->update(strip_null_array_entries($data), ‘id = ‘. (int)$id);