$arr =array('username','admin');
foreach($_GET as $k=>$v)
if(array_search($k, $arr))
$results[$k] = $v;
print_r($results); // prints nothing and I get a
//$results is undefined error
$_GET contains:
(
[r] => p/p
[i] => 9
[_s] => true
[r] => 10
[p] => 1
[s] => username
[o] => asc
[username] => bd
)
so I would expect my $results array to contain ‘bd’ but instead it is undefined.
array_searchreturns the key. Forusernamethat key is0, which evaluates tofalse. You need to check forif (array_search($k, $arr) !== false). You should also initialize$resultsbefore the loop, in case none of the keys are present, otherwise$resultsis never defined.A much shorter way to do the same thing would be: