phparraysarray-flip

Using array_flip With or Without a Value


Code used for processing form $_POST submissions is working well on most forms but suddenly broke on a new set of forms. I can't see any difference in the forms themselves as it's based purely on the posted values and I have it fixed but I am curious why the sudden problem.

There are some cases where specific post values are not to be processed and those, when they are not needed, are in $RemoveFields as a comma-separated list which is converted to an array and on the one set of forms, it doesn't matter if $RemoveFields has any value or not but on the other set it crashes when empty.

By adding a conditional I was able to make it work but can anyone tell me what the problem is on the original code? Both the old and new are below. The first works on only some of the forms while the second seems to work on all.

The original code:

// Remove unneeded fields specified in $RemoveFields variable
if (isset($RemoveFields) && !is_array($RemoveFields)) $RemoveFields = array($RemoveFields);
$filteredarray = array_diff_key($_POST, array_flip($RemoveFields));

The same code but with a conditional for the $filteredarray value:

// Remove unneeded fields specified in $RemoveFields variable
if (isset($RemoveFields) && !is_array($RemoveFields)) $RemoveFields = array($RemoveFields);
$filteredarray = (isset($RemoveFields)) ? array_diff_key($_POST, array_flip($RemoveFields)) : $_POST;

Solution

  • In the original code, you call array_flip($RemoveFields) even when $RemoveFields is not set. This fails because the argument to array_flip() must be an array.

    You should use isset() to protect both lines of code:

    if (isset($RemoveFields)) {
        if (!is_array($RemoveFields)) {
            $RemoveFields = array($RemoveFields);
        }
        $filteredarray = array_diff_key($_POST, array_flip($RemoveFields));
    } else {
        $filteredarray = $_POST;
    }