0

When I declare a variable, for example $a with a value 0, and then in a function I alter that value and re-declare $a I cannot access to that new value outside the function.

$a = 0;

function func(){
  for ($i = 0; $i<=10; $i++){
    $a += 1;
  }
  var_dump($a);
  echo '<br />';
}

func();
var_dump($a);

For example, at the first var_dump (The one inside the function) the result is 11, and at the 2nd one (outside the function) the value is 0;

  • 1
    what is your question? That looks correct. What you might be thinking of is using: `$GLOBALS["a"]` which needs to be used inside your function, *func*, but you can also denote variables with the *global* keyword. See: http://php.net/manual/en/language.variables.scope.php – Fallenreaper Jun 19 '18 at 02:08
  • Yes, you have correctly described how variable scopes work in PHP. There are various ways to get `$a` into scope inside your function. – Greg Schmidt Jun 19 '18 at 02:12
  • Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) –  Jun 19 '18 at 02:51
  • Make sure you assign the answer for which ever one suits you. – Fallenreaper Jun 19 '18 at 13:30

2 Answers2

1

The scope of a variable is local to the function it is in, unless you define it as such. For example, you would need to define $a in your function as a global.

$a = 0
function func(){
    global $a;
    for ($i = 0; $i < 10; $i++){
        $a += 1
    }
    var_dump($a)
}
func()
var_dump($a)
Fallenreaper
  • 10,222
  • 12
  • 66
  • 129
0

You need use global:

<?php
$a = 0;

function func() {
    global $a;
    for ($i = 0; $i<=10; $i++) {
         $a += 1;
    }

    var_dump($a);
    echo '<br />';
}

func();
var_dump($a);