开发者

Array issue within function

I have:

<?php
$a=array('x'=>3,'y'=>6,'z'=>12);  //NOTE THIS*** position 1
echo func(5);

functi开发者_StackOverflow社区on func($c)
{
  $a = array('x'=>3,'y'=>6,'z'=>12);  //NOTE THIS*** position 2
  $previous = null;
  foreach($a as $k => $v)
  {
     if($v > $c) // This part was unclear, so it could be >= instead
     {
        return $previous;
     }
     $previous = $k;
  }
  return $previous;
}

Now, when I have the array $a inside the function (position 2), it works perfect. However, when I place $a outside the function (position 1) it does not work.

Why is this?


Functions can only access data within their scope.

$a defined in position one is in the global scope, if you want to access that in the function you need to pass it as an argument to the function.

Or you can add the line in the function

global $a;

Which brings $a into the current scope from the global scope.

Have a read of Variable Scope from the PHP documentation.


This has to do with variable scope in PHP. You can check that here: http://php.net/manual/en/language.variables.scope.php

Declaring $a in position 1 makes it global. In the way you want to access it, you need to use the global keyword: global $a;


The $a at position one is "out of scope". A function does not have access to variables declared outside of it, unless specifically passed in as a parameter.

See PHP variable scope.

You can give the function access via the global keyword:

$a = array();

function myFunc() {
   global $a;
   // do something with $a here
}

... but note that the use of global variables is generally considered bad practice and is frowned upon.


PHP can not use global variables inside functions unless you declare them:

function func($c)
{
  global $a;
  # The rest of the code.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜