0

I have some array in global scope lets say

$t[0][1] = "a";

how to I access the position from a function?

function fc(){
   echo /* $t[0][1]*/
}

I went through some articles about global variables, but I have not found a solution, every guide is for a single variable

tried:

echo $GLOBALS['t[0][1]'];
echo $GLOBALS['t'][0][1];
echo $GLOBALS['t']['0']['1'];

or tried this

$t[0][1] = "a";
function fc(){
   global $t
   echo  $t[0][1];
}

and none worked .... Any help with this?

Thanks in advance :)

4
  • Do you use any kind of framework? Also you called the function, right?! Commented May 30, 2017 at 10:43
  • pass it as a parameter Commented May 30, 2017 at 10:43
  • pass as a parameter:- stackoverflow.com/a/42393334/4248328 Commented May 30, 2017 at 10:47
  • Missing a ; in global $t Commented May 30, 2017 at 11:20

1 Answer 1

2

You have two options, one of which has already been mentioned in the comments by @Akintunde.

Pass it as an argument:

function fc($arr) {
  print_r($arr);
}
fc($t);

If you intend to modify it, pass it by reference:

function fc(&$arr) {
  $arr[0] = 'test';
}
fc($t);
echo $t[0];

You have already mentioned the global method, which is likely not working due to scope, see: http://php.net/manual/en/language.variables.scope.php. But I can not stress this enough, use of global and $GLOBALS should be avoided at all costs, it is a terrible programming practice and will cause you many headaches down the track.

Another method that keeps your variables out of the scope of the external application is to put everything into your own static class, this will prevent accidental variable reuse.

class MyClass
{
  private static $t = [];

  public static function set($index, $value)
  {
    self::$t[$index] = $value;
  }

  public static function get($index)
  {
    return self::$t[$index];
  }
}

MyClass::set(0, 'test');
echo MyClass::get(0) . "\n";

And if you want to ensure your class doesn't clash with an existing class, namespace it: http://php.net/manual/en/language.namespaces.php

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that has done its magic. used & solution and works well :)

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.