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?

More than 3 years have passed since last update.

PHP学習メモ②

Last updated at Posted at 2020-08-18

### 条件分岐

PHP
$score = 55;

if($score >= 80){
  echo "Great!" . PHP_EOL;
}elseif($score >=60)
  echo "Good!" . PHP_EOL;
else{
  echo "OK!" . PHP_EOL;
}

# ifの場合には、「;」はいらない
# {}で囲まれている内容をブロックという

### 論理演算子

PHP

# 悪い例
$score = 60;
$name = "taguchi";

if($score >= 50 ){
  if($name === "taguchi"){
    echo "Good job!" . PHP_EOL;
  }
}

# 《論理演算子》
# && and なおかつ
# || or  もしくは
# !  〜ではない

# 良い例
$score = 60;
$name = "taguchi";

if($score >= 50 && $name === "taguchi"){
    echo "Good job!" . PHP_EOL;
}

### 条件分岐

PHP
#悪い例
# 「===」が並んでいるときはswichを使う
$signal = 'blue';

if ($signal === 'red') {
  echo 'Stop!' . PHP_EOL;
} elseif ($signal === 'yellow') {
  echo 'Caution!' . PHP_EOL;
} elseif ($signal === 'blue'){
  echo 'Go!' . PHP_EOL;
}

PHP
#良い例
$signal = 'blue';

switch($signal){
  case "red":
    echo 'Stop!' . PHP_EOL;
    break;
  case "blue":
    echo 'Go!' . PHP_EOL;
  break;

  case "yellow":
    echo 'Caution!' . PHP_EOL;
  break;
}
PHP
# 指定したケース以外の場合
  default;
  echo "Wrong signal" . PHP_EOL;
  break;

### 繰り返し構文

PHP
for ($i = 1; $i <= 5; $i++){
  echo "Hello" . PHP_EOL;
}
PHP
for ($i = 1; $i <= 10; $i++) {
  if($i === 4){
    continue;
  }
  echo $i . PHP_EOL;
}

# 「continue」を使って、4の処理だけをスキップできる
PHP
for ($i = 1; $i <= 10; $i++) {
  if($i === 4){
        break;
  }
  echo $i . PHP_EOL;
}

# 「break」を使って、4までの処理で止める
PHP
$hp = 100;

while($hp > 0){
  echo "Your HP:$hp" . PHP_EOL;
  $hp -= 15;
}
# 条件を書き忘れると、無限ループ
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?