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.
It is possible to re-write your function using a combination of:
array_intersect_keyto remove extra keysarray_mergeto add missing keysarray_mapto change every thing to NULL or integerHowever, this only makes it complicated. The slickest way IMO is this:
Output: