1

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

7
  • Did you test it? Your example uses an array key [4] on a scalar variable $var1. If not for that, it would work. Commented Aug 7, 2012 at 20:04
  • 7
    That's an infinite loop. Commented Aug 7, 2012 at 20:04
  • 2
    As long as the variable is defined outside of the loop scope, it is accessible outside of the loop. Commented Aug 7, 2012 at 20:04
  • Sorry; I can't figure out what that's trying to do - you set up $var1 as an integer, but you're treating it as an array in the echo at the end? Commented Aug 7, 2012 at 20:05
  • 2
    @Matt in PHP, the scope isn't limited inside loops (like most other languages) - php.net/manual/en/language.variables.scope.php Commented Aug 7, 2012 at 20:06

2 Answers 2

8
<?php
  $arr = array();
  for ($i = 1; $i < 10; $i++){
      $arr[$i - 1] = $i;
  }
  echo $arr[4]; // This would give 5.
?>
Sign up to request clarification or add additional context in comments.

1 Comment

indeed, this is what I was going for though.
0

You're not changing the value of $i in your loop, which would cause it to go on forever, I'm afraid. Also, you define $var1 as a number, but then you're trying to access it as though it were an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.