如何仅在循环的第一次迭代中执行特定代码块?

Sam*_*ami 1 php

如何为only循环的第一次迭代执行特定的代码块?

原理图

Dav*_*vid 7

你的意思是问"如何为循环的第一次迭代执行特定的代码块"?使用标准for循环,您只需检查计数器,例如:

for ($i = 0; $i < count($images); i++) {
    if ($i == 0) {
        // do this once
    }
    // do this always
}
Run Code Online (Sandbox Code Playgroud)

使用foreach循环,您可以引入某种标志值,例如:

$i = 0;
foreach ($images as $image) {
    if ($i++ == 0) {
        // do this once
    }
    // do this always
}
Run Code Online (Sandbox Code Playgroud)

或者也许是一个布尔标志:

$firstIteration = true;
foreach ($images as $image) {
    if ($firstIteration == true) {
        // do this once
        $firstIteration = false;
    }
    // do this always
}
Run Code Online (Sandbox Code Playgroud)

当然,所有这些都引出了为什么这需要在循环中的问题.考虑这样的事情:

// do this once
foreach ($images as $image) {
    // do this always
}
Run Code Online (Sandbox Code Playgroud)

如果它只应在集合中包含元素时执行,则可以轻松检查:

if (count($images) > 1) {
    // do this once
}
foreach ($images as $image) {
    // do this always
}
Run Code Online (Sandbox Code Playgroud)

最终,循环用于调用集合中每个元素的操作.如果要为整个集合调用一次操作,则该操作可能不属于循环.