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?

配列関数・4回目

Posted at

はじめに

配列関数の整理。4回目。

array_map

要素を取得・加工し新たな配列を生成する。

array_map.php
$data = [1, 2, 3];
$result = array_map(function ($v) { return $v * $v; }, $data);
print_r($result); // Array ( [0] => 1 [1] => 4 [2] => 9 )

array_filter

配列の内容をコールバック関数で判定し、その中でtrueと判定された要素だけを取得する。

array_filter.php
$data = ['フレンチブルドッグ', 'ヨークシャーテリア', 'ダックスフント', 'ポメラニアン', 'コーギー'];
$result = array_filter($data, function($v) {
    return mb_strlen($v) < 8;
});
print_r($result); // Array ( [2] => ダックスフント [3] => ポメラニアン [4] => コーギー )

array_reduce

配列内の要素を順に処理して一つにまとめる。

array_reduce.php
$data = [2, 4, 6, 8];
$multi = array_reduce($data, function($result, $v) {
    return $result + $v;
}, 1);
print_r($multi); // 384
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?