0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

だいたいわかるPHPのコールバック関数のサンプル

Posted at

しょっちゅう忘れるので、だいたいわかる感じで書いた。

array_walkのサンプル

FizzBuzz.php
<?php
$arr = range(1,100);


array_walk($arr, "FizzBuzz");

function FizzBuzz($val, $index){
    echo ($index + 1)." : ";
    if($val % 15 == 0){
        echo "FizzBuzz".PHP_EOL;
    } else if ($val % 5 == 0){
        echo "Buzz".PHP_EOL;
    } else if ($val % 3 == 0){
        echo "Fizz".PHP_EOL;
    } else {
        echo $val.PHP_EOL;
    } 
}
// 出力結果(一部)
1 : 1
2 : 2
3 : Fizz
4 : 4
5 : Buzz
...
15 : FizzBuzz


usortのサンプル

usortSample.php
<?php
//以下の配列を末尾の数字順にソートをしたいみたいなケース
$a = ["A-1", "B-3", "C-4", "D-2", "E-5"];

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}

function cmp($a, $b)
{
    $numA = substr($a, -1);
    $numB = substr($b, -1);
    
    if ($numA == $numB) {
        return 0;
    }
    return ($numA < $numB) ? -1 : 1; 
    //比較関数は、最初の引数と二番目の引数の比較結果を返します。
    //最初の引数のほうが二番目の引数より大きい場合は正の数を、
    //二番目の引数と等しい場合はゼロを、
    //そして二番目の引数より小さい場合は負の数を返す必要があります。
}
?>
// 出力結果
0: A-1
1: D-2
2: B-3
3: C-4
4: E-5

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?