简体   繁体   English

在循环PHP外使用循环变量

[英]Using loop variable outside the loop PHP

This is probably very simple but I cannot figure it out and my searches have come up blank. 这可能很简单,但我无法弄清楚,搜索结果空白。

Here is what I have in mind: 这是我的想法:

<?php

$var1 = 0.0;
for ($i=1;$i<10;$i++){
    $var1 = $var1 + $i;
}
echo $var1[4]; // This would give 0, I believe.
?>

I hope my example made it clear what I'm trying to do, and I'm sure there is a simple solution, I just unfortunately cannot find it. 我希望我的示例清楚地说明了我要做什么,并且我确定有一个简单的解决方案,但是不幸的是我找不到它。

Thanks, Sam 谢谢山姆

<?php
  $arr = array();
  for ($i = 1; $i < 10; $i++){
      $arr[$i - 1] = $i;
  }
  echo $arr[4]; // This would give 5.
?>

You're not changing the value of $i in your loop, which would cause it to go on forever, I'm afraid. 恐怕您没有在循环中更改$ i的值,这将使其永远持续下去。 Also, you define $var1 as a number, but then you're trying to access it as though it were an array. 另外,您将$ var1定义为一个数字,但是随后您试图像访问数组一样访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM