Help us understand the problem. What is going on with this article?

無名関数の使い方について

More than 1 year has passed since last update.

無名関数とは

無名関数とは、関数名を持たない関数のこと。
変数に代入したり、引数としてコールバック関数を要求する箇所で使用することができる。(PHP5.3以降から使用可能)

つかいどころ

限定した箇所でしか使用しない関数を宣言したい場合

関数

array_walk() , array_map() , array_filter() など...

使用例

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>無名関数について</title>
    <link rel="stylesheet" href="">
</head>
<body>
    <?php 
        $nature = array('water','forest','tree','cloud','sun','river');
        $filter_less5 = function($text) {
            return strlen($text) < 5;
        };
        echo '<p>5文字未満のデータ</p>';
        echo '<ul>';
        $filter_less5 = array_filter($nature,$filter_less5);
        foreach($filter_less5 as $data) {
            echo '<li>'.h($data).'</li>';//tree,sun
        }
        echo '</ul>';

        $filter_equal5 = array_filter($nature,function($text){
            return strlen($text) === 5;
        });
        echo '<p>5文字のデータ</p>';
        echo '<ul>';
        foreach($filter_equal5 as $data) {
            echo '<li>'.h($data).'</li>'; //water,cloud,river
        }
        echo '</ul>';

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

補足

strlen → バイト数を計算する(全角文字などは、2文字になる 例:あ → 2 あa → 3)
mb_strlen → 文字列の文字数をカウントする (あ → 1 あa → 2)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした