tags:

views:

299

answers:

3

Storing an array submitted from forms stores elements with null values. Is there a way to store only non null fields into the php array?

$_SESSION['items'] = $_POST['items'];

is my current code.

+3  A: 
# Cycle through each item in our array
foreach ($_POST['items'] as $key => $value) {
  # If the item is NOT empty
  if (!empty($value))
    # Add our item into our SESSION array
    $_SESSION['items'][$key] = $value;
}
Jonathan Sampson
+4  A: 

You should take a look at array_filter(). I think it is exactly what you are looking for.

$_SESSION['items'] = array_filter($_POST['items']);
Till Theis
it worked without the isset. amazing some of php functions make life so easy. Thanks buddy!
payling
Right, I forgot about the automatic conversion and about the fact that empty form values are not NULL but empty strings.
Till Theis
A: 

Like @Till Theis says, array_filter is definitely the way to go. You can either use it directly, like so:

$_SESSION['items'] = array_filter($_POST['items']);

Which will give you all elements of the array which does not evaluate to false. I.E. you'll filter out both NULL, 0, false etc.

You can also pass a callback function to create custom filtering, like so:

abstract class Util {
    public static function filterNull ($value) {
        return isset($value);
    }
}

$_SESSION['items'] = array_filter($_POST['items'], array('Util', 'filterNull'));

This will call the filterNull-method of the Util class for each element in the items-array, and if they are set (see language construct isset()), then they are kept in the resulting array.

PatrikAkerstrand