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?

[php初心者]入力値の受け取り方[アルゴリズム]

0
Posted at

はじめに

phpを学び始めたばかりの初心者です。
Atcoderをやりはじめましたが入力値の受け取り方がわからなかったので、まとめました。

入力値が1つの場合

$input_lineに入力値を代入するには、

$input_line = trim(fgets(STDIN));

$input_line = fgets(STDIN)だけだと、標準入力から1行読み取り、改行文字を含む文字列を返す場合がある。
先頭・末尾の空白や改行を取り除く目的でtrim()も使用。

数値(整数)として扱う場合は、intval()を使って変換する。

$input_line = intval(trim(fgets(STDIN)));

STDINとは、phpがあらかじめ用意している標準入力(standard input)を表すもの。

入力値が複数の場合

例えば、10 3 5と入力される場合、それぞれを$X$Y$Zに代入するには

[$X, $Y, $Z] = array_map('intval', explode(' ', trim(fgets(STDIN))));

trim(fgets(STDIN))で入力された行の空白や改行を取り除き、explode(' ', ...)で半角スペースを区切りとして文字列を分割している。

array_mapは配列の各要素に指定した関数を適用する関数。
array_map('intval', ...)で文字列を整数に変換した配列を作り、[$X, $Y, $Z]に代入している。

参考

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?