0

Get array declared outside function to every function without passing argument in php

<?php
  $arr2= array('00','12','23','73'); 

  function f1() {
    print_r($arr2);
  }

  f1();
?>

Here we can pass the array f1($arr2), but I want to know whether we acess array inside the function 'f1' without passing, something like setting global or some else ?

I want only to know, whether it is possible or not ?

hakre
  • 193,403
  • 52
  • 435
  • 836
Justin John
  • 9,223
  • 14
  • 70
  • 129
  • 1
    what is the context? what are these functions? what is certain use case? you know, there can be many different answers, depends on the particular case. Marking the question as not a real one. – Your Common Sense Jan 15 '12 at 07:15
  • If you have many functions that must all work with the same data, you'd usually go for a class and/or object. Using `global` is not a good solution to this problem. – deceze Jan 15 '12 at 07:20
  • @deceze: I followed a structure which is not using class, that is why I went to [global]. – Justin John Jan 15 '12 at 07:24

3 Answers3

3

use global:

  function f1() {
    global $arr2;
    print_r($arr2);
  }

However, as @steven already point out, it is considered bad practice.

These thread talk about why global variable is considered bad:

Community
  • 1
  • 1
ariefbayu
  • 21,849
  • 12
  • 71
  • 92
  • There are many arrays are declared inside a function and it can be used in various other functions. So I put these arrays outside the function set it 'global' in every function where I need this. Is it bad idea. – Justin John Jan 15 '12 at 07:11
1

It's possible using globals however it is typically considered a bad practice.

Example from php.net:

<?php
function test() {
    $foo = "local variable";

    echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
    echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";
test();
?>
Steven
  • 1,107
  • 1
  • 8
  • 21
1

Use global $arr2:

<?php
  $arr2= array('00','12','23','73'); 

  function f1() 
  {
     global $arr2;

     print_r($arr2);
  }

  f1();
?>
Zul
  • 3,627
  • 3
  • 21
  • 35