1 minute read

学んだこと

文字列連結

  • 連結する際に.を使うことで文字列を連結することができる。
  • echo を複数書いても良いが、.で連結したほうが、見やすい。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    date_default_timezone_set('Asia/Tokyo');
    echo '現在は'.date('G時 i分 s秒').'です'
    ?>
</body>
</html>

  • echo の引数を複数渡すことで、文字列連結を行うこともできる。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    date_default_timezone_set('Asia/Tokyo');
    echo '現在は', date('G時 i分 s秒'), 'です'
    ?>
</body>
</html>

オブジェクトで日付を扱う

  • C++や C#などと同じように、オブジェクト志向でコードを記述することもできる。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    $today = new DateTime();
    $today->setTimezone(new DateTimeZone('Asia/Tokyo'))
    echo '現在は、'. $today->format('G時 i分 s秒'). 'です。'
    ?>
</body>
</html>

変数について

  • $変数名で宣言することができる。
  • 以下の様に、HTML タグ内に、<?php ?>を記述し、中に処理を書くこともできる。
  • 変数名を日本語にすることもできるが、一般的には英語を使用する。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    $sum = 100 + 1050 + 200;
    echo '合計金額は、'. $sum;
    ?>
    <p>合計金額は、<?php echo $sum; ?>円です</p>
    <p>税込価格は、<?php echo $sum * 1.1 ?>円です</p>
</body>
</html>

繰り返し構文(while)

  • C++や C#と同様、while(条件式)で記述することができる。
  • while(条件式){処理}で処理を囲むでも良いがwhile(条件式): 処理でも OK
  • while(条件式): 処理で記述する際は、処理の終わりに必ず、endwhile を忘れずに記述する。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    $i = 1;
    while($i < 366):
        echo $i . '<br>';
        $i = $i + 1;
    endwhile;
    ?>
</body>
</html>

繰り返し構文(for)

  • 他の言語と同じ書き方で書くことができる。
    • for(初期値; 条件式; 更新処理)
    • endforを最後に書き忘れないように。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    $i = 1;
    for($i = 1; $i < 366; $i = $i++):
        echo $i . '<br>';
    endfor;
    ?>
</body>
</html>

Tags:

Updated: