2018년 3월 13일 화요일

[PHP예제] 040 익명 함수

익명 함수(anonymous function)란, 이름 그대로 함수명이 없는 함수다.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>익명 함수</title>
</head>
<body>
<div>
<?php
$nature = array('water', 'forest', 'tree', 'cloud', 'sun', 'river');

$filter_less5 = function( $text ) {
    return strlen( $text ) < 5;
};

$filtered_less5 = array_filter( $nature, $filter_less5 );

echo '<p>다섯 문자 미만의 데이터: </p>';
echo '<ul>';
foreach( $filtered_less5 as $data ) {
    echo '<li>' . h($data) . '</li>';
}
echo '</ul>';


$filtered_equal5 = array_filter( $nature,
    function( $text ) {
        return strlen( $text ) == 5;
    }
);

echo '<p>다섯 문자의 데이터: </p>';
echo '<ul>';
foreach( $filtered_equal5 as $data ) {
    echo '<li>' . h($data) . '</li>';
}
echo '</ul>';

function h($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
?>
</div>
</body>
</html>




댓글 없음:

댓글 쓰기