dongwu9647
dongwu9647
2015-12-12 23:40

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

  • while-loop
  • php

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条回答