2Answers

global array in php

3.7k Views
  • 12
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

global array in php

i have to function in two different files. one of them should add a new item to an array each time is called and the array should be accessible .what i did for it is :

function1(){

   global $array;

   $array[] = 'hi';

}

but it just create one item in array even if i call this function 4 times .

What you did should work.

<?php

function function1(){

   global $array;

   $array[] = 'hi';

}
function1();
function1();
function1();
print_r($array);

Test it.

You probably have another problem. Please note that the lifetime of all variables is the current run of your script. They won't exist in a successive run. For that you need to use some sort of persistence like session, cookie, file system, database.

For more help post your complete code.

  • 11
Reply Report

I'm a bit confused by the wording of your question. When you say "i have to function in two different files." does you mean you have "two" functions?

If you have two functions both trying to use your $array variable, you'll need to call global $array; in both functions.

The reason for this is that global is a bit misleading. All it's really doing is assigning a reference to a member of $_GLOBALS to a variable in the local scope which has the same name as the $_GLOBALS index. In other words, if you do something like this:

 global $variable;

it's essentially the same thing as saying this:

 $variable =& $_GLOBALS['variable'];   (assign by reference)

The actual variable $variable is still scoped at the function level, it just happens to have a reference to a global variable.

The implication of this is that if you don't define global $variable in every function, you're just creating a brand new variable within the scope of that function. When the function ends, the variable is unset and any changes made to it within the function are lost.

With all of that said, global variables still tend to be a bad idea. It's a lot clearer if you just maintain a local variable, and pass it as a parameter to other functions when needed.

  • 5
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions