J.BF Story
[PHP] array_filter을 통해 배열 요소 필터링 본문
PHP 내장 함수인 array_filter을 통해 조건에 부합하는 배열 요소만 필터링할 수 있다.
PHP: array_filter - Manual
Depending on the intended meanings of your "empty" array values, e.g., null and empty string, vs. an integer 0 or a boolean false, be mindful of the result of different filters. null, 'nullstring' => '', 'intzero' => 0, 'stringzero' => '0', 'false' =>
www.php.net
다음과 같은 방법으로 콜백함수와 모드를 통해 필터링할 수 있다.
- 명명 필터 함수 사용
- 익명 필터 함수(클로저)사용
- 익명 필터 함수(클로저)에 외부 변수값 전달 (use)
- 필터링 모드 사용 (기본은 array의 value를 통해 필터링)
- array의 key를 통해 필터링 (ARRAY_FILTER_USE_KEY)
- array의 key, value를 통해 필터링 (ARRAY_FILTER_USE_BOTH)
명명 필터 함수 사용
$test_arr = array("test1" => 1, "test2" => 2, "test3" => 3, "test4" => 4);
function filter_func($v) {
return ($v > 2);
}
$result = array_filter($test_arr, "filter_func");
print_r($result); // Array ( [test3] => 3 [test4] => 4 )
익명 필터 함수(클로저) 사용
$test_arr = array("test1" => 1, "test2" => 2, "test3" => 3, "test4" => 4);
$result = array_filter($test_arr, function ($v) { return ($v > 2); });
print_r($result); // Array ( [test3] => 3 [test4] => 4 )
익명 필터 함수(클로저)에 외부 변수값 전달 (use)
$test_arr = array("test1" => 1, "test2" => 2, "test3" => 3, "test4" => 4);
$threshold = 2;
$result = array_filter($test_arr, function ($v) use ($threshold) { return ($v > $threshold); });
print_r($result); // Array ( [test3] => 3 [test4] => 4 )
** 클로저(closure)의 use를 사용하여 외부 변수값 전달
필터링 모드 사용
array의 key를 통해 필터링 (ARRAY_FILTER_USE_KEY)
$test_arr = array("test1" => 1, "test2" => 2, "test3" => 3, "test4" => 4);
$result = array_filter($test_arr, function ($k) {
return in_array($k, ["test2", "test3"]);
}, ARRAY_FILTER_USE_KEY);
print_r($result); // Array ( [test2] => 2 [test3] => 3 )
** 'ARRAY_FILTER_USE_KEY'를 통해 모드를 설정해준다.
array의 key, value를 통해 필터링 (ARRAY_FILTER_USE_BOTH)
$test_arr = array("test1" => 1, "test2" => 2, "test3" => 3, "test4" => 4);
$result = array_filter($test_arr, function ($v, $k) {
return (in_array($k, ["test2", "test3"]) && ($v > 2));
}, ARRAY_FILTER_USE_BOTH);
print_r($result); // Array ( [test3] => 3 )
** 콜백함수의 파라미터는 array의 value, key 순이다.
** 'ARRAY_FILTER_USE_BOTH'를 통해 모드를 설정해준다.