DAY 10
0
Software Development

# 條件控制

• if
• if...else
• if...elseif...else
• switch

## if

``````if (條件式) {
條件成立才執行內容;
}

``````

``````\$user = 'Kao';
if (\$user
== 'Kao') {
echo 'Hi, Kao';
}
``````

## if...else

``````if (條件式) {
條件成立才執行內容;
} else {
條件不成立時執行的內容;
}
``````

``````<?php
\$user = 'SoJ';
if (\$user == 'Kao') {
echo 'Hi, Kao';
} else {
echo 'Hi, I don\'t know you!';
}
``````

## if...elseif...else

``````if (條件式a) {
條件a 成立才執行內容;
} elseif (條件b) {
條件b 成立時執行的內容;
} else {
條件a ,條件b 都不成立時才執行內容;
}

```php
<?php
\$bag_height = 80;
if (\$bag_height > 100) {
echo 'This bag is big size.';
} else if (\$bag_height > 40 && \$bag_height <= 100) {
echo 'This bag is middle size.';
} else {
echo 'This bag is samll size.';
}
``````

## switch

``````switch (自定義變數) {
case 條件值1:
自定義變數等於條件值1，就執行的內容;
break;
case 條件值2:
自定義變數等於條件值2，就執行的內容;
break;
.
.
.
default:
上述條件都不滿足才執行這裡的內容;
}

```php
<?php
\$point = ['x' => 1,'y' => -1];
switch(\$point) {
case (\$point['x']>0 && \$point['y']>0):
echo '第一象限';
break;
case (\$point['x']<0 && \$point['y']>0):
echo '第二象限';
break;
case (\$point['x']<0 && \$point['y']<0):
echo '第三象限';
break;
case (\$point['x']>0 && \$point['y']<0):
echo '第四象限';
break;
}
``````

# 迴圈

• while
• do...while
• for
• foreach

## while

``````while (條件式) {
條件成立才執行內容;
}
//直到條件不符合才跳離
``````

``````<?php
\$multiplicand = 2;
\$multiplier = 1;
while (\$multiplier < 10) {
echo \$multiplicand.' x '.\$multiplier.' = '.\$multiplicand * \$multiplier."</br>";
\$multiplier++;
}
``````

## do...while

``````do {
執行內容;
} while (條件式);
``````

``````<?php
\$multiplicand = 2;
\$multiplier = 1;
do {
echo \$multiplicand.' x '.\$multiplier.' = '.\$multiplicand * \$multiplier."</br>";
\$multiplier++;
} while (\$multiplier < 1);
``````

## for

``````for(變數初始值;條件式;變數計次方式) {
執行內容;
}
``````

``````<?php
for(\$i=2;\$i<10;\$i++){
for(\$j=2;\$j<10;\$j++) {
echo "\$i x \$j = ".(\$i * \$j).'</br>';
}
echo '--------</br>';
}
``````

## foreach

foreach 的一般表示法比較難解釋，foreach 的主要用法是用來遍歷一個 object 或是 array。我們直接看範例。

``````<?php
\$class = [
0=>['name' => 'Kao', 'age' => 20],
1=>['name' => 'SoJ', 'age' => 21]
];

foreach (\$class as \$profile){
echo 'name : '.\$profile['name'].' ; ';
echo 'age : '.\$profile['age'].'</br>';
}
``````