Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 循环不计数_Php_Loops - Fatal编程技术网

Php 循环不计数

Php 循环不计数,php,loops,Php,Loops,我试图得到以下代码来添加多少人可以退休而不是退休。代码将显示,但不会添加。我做错了什么 <?php $canRetire= 0; $notRetired = 0; $agesFile = fopen("ages.txt", "r"); $nextAge = fgets($agesFile); while (feof($agesFile) ){ list($agesFile)=explode(":",$nextAge); if ($agesFile > 65){

我试图得到以下代码来添加多少人可以退休而不是退休。代码将显示,但不会添加。我做错了什么

<?php
$canRetire= 0;
$notRetired = 0;

$agesFile = fopen("ages.txt", "r");
$nextAge = fgets($agesFile);
while (feof($agesFile) ){
   list($agesFile)=explode(":",$nextAge);
   if ($agesFile > 65){ 
       $canRetired = $canRetired + 1;
   }
   else{
       $notretired = $notRetired + 1;
   }
   $nextAge = fgets($agesFile);
}
fclose ($agesFile);

print("<p>Number of people can retired : $canRetired</p>");
print("<p>Number of people not retired: $notRetired</p>");
?>
不应该是一段时间吗!费奥夫

当到达文件末尾时要停止

另外,看起来您有一些拼写错误:

$notretired = $notRetired + 1;
请注意,R在左侧是小写,在右侧是大写

同样,在开始时,您有$canRetire,在循环中的if条件中,您有$canRetire


还有一点提示:$notRetired=$notRetired+1;与$notRetired++相同

根据您定义的变量对案例和类型进行了一些修改。看起来变量$canRetire与$canretired不匹配

使用whilefeof$fh基本上是说,为EOF这样做。这使得整个循环毫无用处。使用时!feof$fh将允许您循环直到EOF

<?php
$canRetired= 0;
$notRetired = 0;

$agesFile = fopen("ages.txt", "r");
$nextAge = fgets($agesFile);
while (!feof($agesFile) ){
   list($agesFile)=explode(":",$nextAge);
   if ($agesFile > 65){ 
       $canRetired = $canRetired++;
   }
   else{
       $notRetired = $notRetired++;
   }
   $nextAge = fgets($agesFile);
}
fclose ($agesFile);

print("<p>Number of people can retired : $canRetired</p>");
print("<p>Number of people not retired: $notRetired</p>");
?>

$notretired=$notretired+1;请注意变量名称中的R vs R一种向变量添加+1的更快方法,就是简单地执行$CANReired++;还有,你可能是说“当”吧!feof而feof$agesFile{-你是说while!feof$agesFile?你想在文件结束时停止,而不是离开文件时停止。我认为这个问题不是一个好的格式,因为它由印刷错误和一个非常简单的错误组成。@crush你还注意到了什么吗?@JanDvorak,现在是完整的解决方案。他最初只提到while文件开头也有一个输入错误:$canRetire=0;但这不应该影响结果。