LoginSignup
1
2

More than 3 years have passed since last update.

PHPの基本操作① 「簡単な出力と構文、配列、連想配列、少数、フォーマット」

Last updated at Posted at 2021-04-22

参考書籍

よくわかるPHPの教科書 PHP7対応版

他記事リンク

文章を表示

print関数を使用して出力する

文章を表示
<?php
  print('一番簡単な出力です');
?>

現在時刻

date関数を使用して出力する
※date_dafult_timezone_setでタイムゾーン(どこの国の時刻か)を設定する

  • 時間 → G時
  • 分 → i分
  • 秒 → s秒
  • タイムゾーン → Asia/Tokyo
現在時刻
<?php
  date_default_timezone_set('Asia/Tokyo');
  print(date('G時 i分 s秒'));
?>  

繰り返し(for)

for(初期値; 条件式; 処理後に実行される処理)で条件を満たす場合、繰り返し{}内の処理を実行します。

繰り返し(for)
<?php
  for($i = 1; $i <= 365; $i++){
    print($i . "\n");
  }
?>

繰り返し(while)

while(条件式)で条件を満たす場合、繰り返し{}内の処理を実行します

繰り返し(while)
<?php
  $i = 1;
  while ($i <= 365) {
    print($i . "\n");
    $i++;
  }
?>

一年後までのカレンダー

一年後までのカレンダー
<?php
  for($i = 1; $i <= 365; $i++) {
    $day = date('n/j(D)', strtotime('+' . $i . 'day'));
    print($day . "\n");
  }
?>

配列を使う

「曜日」を取得 → date('w')

配列を使う
<?php
  $week_name = ['日', '月', '火', '水', '木', '金', '土'];
  print('今日は' . $week_name[date('w')] . '曜日です');
?>

連想配列を使う

キーを使って、値を取り出す。

連想配列を使う
<?php
  $fruits = [
    'apple' => 'りんご',
    'grape' => 'ぶどう',
    'lemon' => 'レモン',
    'tomato' => 'トマト',
    'peach' => 'もも'
  ];

  foreach ($fruits as $english => $japanese) {
    print($english . ' : ' . $japanese . "\n");
  }
?>

条件分岐

()内の条件に対して「真偽」を判定し、処理を実行します

条件分岐
<?php
  date_default_timezone_set('Asia/Tokyo');
  if(date('G') < 9) {
    print('※ 現在受付時間外です');
  } else {
    print('ようこそ');
  }
?>

少数の切り捨て、四捨五入、切り上げ

少数第一位の値に対して、切り捨て、四捨五入、切り上げを行います。

少数の切り捨て、四捨五入、切り上げ
<?php
  print("切り捨て(floor)" . "\n");
  print("1.4 → " . floor(1.4) . "\n");
  print("1.5 → " . floor(1.5) . "\n");

  print("四捨五入(round)" . "\n");
  print("1.4 → " . round(1.4) . "\n");
  print("1.5 → " .round(1.5) . "\n");

  print("切り上げ(ceil)" . "\n");
  print("1.4 → " . ceil(1.4) . "\n");
  print("1.5 → " . ceil(1.5) . "\n");
?>

書式を整える

sprintf(フォーマットの形式, 最初に代入する値, 2番目に代入する値, .....);
フォーマットの形式 → %桁数d
フォーマットの形式 → %文字数s
記載しない場合には、桁数、文字数は変更されません。
また、文字を数字のフォーマットしようとした場合には0になります。

書式を整える
<?php
  $date = sprintf('%04d年 %02d月 %02d日' , 2018, 1, 23);
  print($date);

  $ngformat = sprintf('%d', 'abc');
  print($ngformat);

  $okformat = sprintf('%s', 'abc');
  print($okformat);
?>
1
2
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
1
2