1

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 Answers 3

4

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

$_SESSION['items'] = array_filter($_POST['items']);
Sign up to request clarification or add additional context in comments.

2 Comments

it worked without the isset. amazing some of php functions make life so easy. Thanks buddy!
Right, I forgot about the automatic conversion and about the fact that empty form values are not NULL but empty strings.
3
# 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;
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.