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.
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.
# 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;
}
You should take a look at array_filter(). I think it is exactly what you are looking for.
$_SESSION['items'] = array_filter($_POST['items']);
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.