简体   繁体   中英

html form arrays how to store into php array not including null elements

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.

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

$_SESSION['items'] = array_filter($_POST['items']);
# 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;
}

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. IE 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM