0

I'm surprised I'm not able to access an array in a function without passing it to the function

$arr = [-4,3,-9,0,4,1]; 
function print_array()
{
    print_r($arr);
}
print_array();

when I run, I'm getting Notice: Undefined variable arr

I though since the array and the function are in the same file, I would be able to access it? Can I not access the array without passing it to the function? I have a bunch of arrays outside, that I need to print in the function. But I don't want to pass each one of them.

Wild Widow
  • 2,359
  • 3
  • 22
  • 34
  • pass $arr like an argument of the function.. `function print_array($arr){print_r($arr);}` – miglio Sep 07 '15 at 21:38
  • Why should you be surprised? It's called [variable scope](http://www.php.net/manual/en/language.variables.scope.php).... scope isn't file-based, it's function-based – Mark Baker Sep 07 '15 at 21:39
  • @MarkBaker but the array is declared outside the function right. I'm confused. – Wild Widow Sep 07 '15 at 21:40
  • It's declared outside the function, so it doesn't exist inside the function unless you explicitly make it available to that function (typically by passing it into the function as an argument) – Mark Baker Sep 07 '15 at 21:40
  • if you want to use $arr inside the function write "global $arr;" before the print_r. but that's not a good way to do things. – Lucian Depold Sep 07 '15 at 21:42
  • Makes sense, thanks everyone for your help. I came from C background, in C you can directly access variables declared outside , in a function without passing them as arguments – Wild Widow Sep 07 '15 at 21:47

0 Answers0