2
1

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 1 year has passed since last update.

【PHP】PHPのuseの使い方

Last updated at Posted at 2022-07-01

useとはスコープ外の変数を関数内で使用できる。

<?php
$people = [
    ['name' => '太郎',  'age' => 19],
    ['name' => '洋子',  'age' => 37],
    ['name' => '美玖',  'age' => 21],
    ['name' => '信也',  'age' => 15],
    ['name' => '裕次郎','age' => 45],
    ['name' => '魁',    'age' => 8],
    ['name' => '達郎',  'age' => 55],
    ['name' => '真治',  'age' => 29]
];

$low = '20歳未満だから子供';
$over = '大人';
$age = 20;

$value = array_map(function($num)use($low,$over,$age){
    return ($num['age'] < $age ? $num['name'].'は'.$low : $num['name'].'は'.$over);
}, $people);

var_dump($value);

結果

array(8) {
  [0]=>
  string(35) "太郎は20歳未満だから子供"
  [1]=>
  string(15) "洋子は大人"
  [2]=>
  string(15) "美玖は大人"
  [3]=>
  string(35) "信也は20歳未満だから子供"
  [4]=>
  string(18) "裕次郎は大人"
  [5]=>
  string(32) "魁は20歳未満だから子供"
  [6]=>
  string(15) "達郎は大人"
  [7]=>
  string(15) "真治は大人"
}
2
1
4

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?