Search code examples
phparraysfilteringassociative-arraysanitization

Sanitize/Filter associative elements in user input array


I would like to validate that an array has and only has "a", "b", and "c" as associate keys, and that the values are either integers or either NULL or 0 (what ever is easier).

For instance, array('a'=>123,'b'=>'abc', 'd'=>321) should be converted to array('a'=>123,'b'=>0, 'c'=>0).

I can do something like the following, but it is a little difficult to read, and will become big if I don't just have 3 elements but 300.

$newArr=array(
    'a' => (isset($arr['a'])) ? (int)$arr['a'] : 0,
    'b' => (isset($arr['b'])) ? (int)$arr['b'] : 0,
    'c' => (isset($arr['c'])) ? (int)$arr['c'] : 0
);

Another option is something like the following:

$newArr = array();
foreach (array('a','b','c') as $key)
{
    $newArr[$key] = (isset($arr[$key])) ? (int)$arr[$key] : 0;
}

I guess this works good enough, however, am curious whether there is some slick array converting function that I don't know about that would be better.


Solution

  • It is possible to re-write your function using a combination of:

    However, this only makes it complicated. The slickest way IMO is this:

    $test = array("a" => 123, "b" => "x", "d" => 123);
    $testcopy = array();
    foreach (array("a", "b", "c") as $key) {
        $testcopy[$key] = array_key_exists($key, $test)
            ? filter_var($test[$key], FILTER_VALIDATE_INT, array("options" => array("default" => NULL)))
            : NULL;
    }
    var_dump($testcopy);
    

    Output:

    array(3) {
        ["a"]=> int(123)
        ["b"]=> NULL
        ["c"]=> NULL
    }