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条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛