> For the complete documentation index, see [llms.txt](https://phper.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://phper.shujuwajue.com/ji-chu/liu-cheng-kong-zhi-yu-ju.md).

# 流程控制与条件判断

## 流程控制语句

**3中流程控制语句**  <br>

* 使用for循环
* 使用foreach循环
* 使用while、list()、each()组合循环

**介绍：**

* for循环，只能遍历索引数组，
* foreach可以遍历索引和关联数组
* 联合使用list(),each()和while循环同样可以遍历索引和关联数组

**区别**  <br>

* list(),each()和while组合不会reset()操作（之前有对数组进行了指针的操作，则使用此方式，则不会重置数组，而是在这个指针往后循环，就会出现数据不完整）
* forreach遍历会对数组进行resrt()操作

示例：

```php
<?php

$data = array('a','b','c');
next($data);  //改变了数组的指针指向

echo 'while循环' . '<br>';
while(list($k,$v) = each($data)){ 
    echo $k . '=' . $v. '<br />'; 
} 

echo 'for循环' . '<br>';
for($i=0;$i< count($data); $i++) {
    echo $i . '=' . $data[$i] . '<br>';
}

echo 'foreach循环' . '<br>';
foreach($data as $k => $v) {
    echo $k . '=' . $v . '<br>';
}
```

输出结果：

```
while循环
1=b
2=c
for循环
0=a
1=b
2=c
foreach循环
0=a
1=b
2=c
```

## 条件判断语句

### **switch...case..语句**

switch后面的控制表达式的数据类型只能是**整型、浮点类型或者字符串**  <br>

continue语句作用到switch的作用类似break;

跳出switch外的循环，可以使用continue2 或者break2；

示例：

```
<?php

$a = 10;
for($i=0;$i< 10;$i++) {
    switch($i){
        case 5:
            break 2;
        default:
            break;
    }

    echo $i.'<br>';
}
```

结果：

```
0
1
2
3
4
```

**效率：**  <br>

如果条件判断比较复杂或者在一个很多次的循环中，那么用switch语句可能会快一些

### php如何优化多个if..else语句的情况？

* 1.尽量把可能性大的判断往前放
* 2.如果条件判断比较复杂或者在一个很多次的循环中，并且判断是一个是整型、浮点类型或者字符串换用switch..case..


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://phper.shujuwajue.com/ji-chu/liu-cheng-kong-zhi-yu-ju.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
