Why does InputFilter allow_empty + required with ArrayInput differ to regular Inputs?

Hi All

I have been having issues dealing with arrays and the InputFilter’s “required” and “allow_empty” options.

It is my understanding that:

  • required = The input array must contain the field name as a key
  • allow_empty = The value for the input can be empty (i.e. empty string, empty array, etc.)

With a standard “Input” type, everything works as expected:

$inputFilter = new InputFilter();

$inputFilter->add([
    'name' => 'textField',
    'type' => Input::class,
    'required' => true,
    'allow_empty' => true,
    'continue_if_empty' => false,
    'filters' => [
        ['name' => StripTags::class],
    ]
]);

$inputFilter->setData([
    'textField' => ''
]);

$result = $inputFilter->isValid(); // true

However, when using the ArrayInput type, an empty array is flagged as invalid:

$inputFilter = new InputFilter();

$inputFilter->add([
    'name' => 'arrayField',
    'type' => ArrayInput::class,
    'required' => true,
    'allow_empty' => true,
    'continue_if_empty' => false,
    'filters' => [
        ['name' => ToInt::class],
    ]
]);

$inputFilter->setData([
    'arrayField' => []
]);

$result = $inputFilter->isValid(); // false
$inputFilter->getMessages(); // [[isEmpty] => Value is required and can't be empty]

Am I misunderstanding how these options are intended to work, or is this possibly a bug?

Hello and welcome to our forums! :smiley:

It corresponds to the tests:

But feel free to open an issue report if you think it should be different.


And please compare with:

$inputFilter->setData([
    'arrayField' => ['']
]);
$inputFilter->setData([
    'arrayField' => [null]
]);

Now I understand (I think)…

When using an ArrayInput, the “allow_empty” option does not mean “the array can be empty”, instead, it means “the elements of the array can be empty”.

Is this the intended behavior? I didn’t find any tests (or docs) that cover the “allow_empty” option with the ArrayInput

This will be reworked and clarified with the next major update of laminas-inputfilter (v3) because this has not been further documented so far.