dongwu9647 2015-12-12 23:40
浏览 114
已采纳

可以在while循环中声明变量吗?

I am trying to understand the basic PHP code in this video, which demonstrates how you can list all the positions of a specific string within a larger string (in this case, all the positions of $find within $string will be listed):

<?php

$find = 'is';
$find_leng = strlen($find);
$string = 'This is a string, and it is an example.';

while ($string_position = strpos($string, $find, $offset)) {
    echo '<strong>'.$find.'</strong> found at '.$string_position.'<br>';
    $offset = $string_position + $find_length;
}

?>

What confuses me is that within the () of the while-loop, it seems that a new variable $string_position is being declared. But doesn't the while-loop take an input of 0 or 1, a Boolean? The $string_position variable is not a true/false variable, it is meant to store the position of the string it is passed with the strpos() function.

The basic while-loop I'm used to uses a comparison operator like this one from from w3schools:

<?php 
$x = 1; 

while($x <= 5) {
    echo "The number is: $x <br>";
    $x++;
} 
?>

Can a variable be declared in a while-loop? And if that is the case, how does it work in this example? This is my first question on Stack Overflow so hopefully I'm posting this in the right place and it's not too newbie of a question.

  • 写回答

2条回答 默认 最新

  • donglankui1263 2015-12-12 23:45
    关注

    Yes, while loops take boolean-like as arguments. By doing

    while ($string_position = strpos($string, $find, $offset)) {
    

    it first executes what is inside the parenthesis, then evaluates the result of that to determine if the loop should quit or not.

    strpos will return False if the needle was not found, so $string_position will be false and as such the evaluation result will also be False and the loop will quit. If the needle is found, then loop continues after the attribution.

    Also it should be noted that strpos might return a non-boolean that evaluates to False, so be careful with that construction.

    Reference on strpos

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算