Michael Studebaker
Michael Studebaker

Reputation: 596

How to create Globals Array

How do you create an array in GLOBALS for php?

for example, I want to do something like this:

$GLOBALS["chapter_names"] = array();

and then

$GLOBALS["chapter_names"][$i] = $row -> CHAPTER_NAME;

inside a while loop

where $i is the index of the array

is this the optimal way to do things?

thanks!

Upvotes: 0

Views: 7024

Answers (4)

Don't use $GLOBALS, it's an outdated and quite dangerous practice. You can read about the Registry pattern - it's an OO solution to the problem. As for your example, it should be completely working.

Upvotes: 0

Sophie Sperner
Sophie Sperner

Reputation: 4556

$GLOBALS["chapter_names"] = array();
foreach ($rows as &$row) {
    array_push($GLOBALS["chapter_names"], $row->CHAPTER_NAME);
}

Upvotes: 6

user470714
user470714

Reputation: 2888

Pretty much exactly as you gave it there. Except you don't need to put an index of $i when you're adding new stuff, unless it needs some specific index. You could just do it something like this:

$GLOBALS['chapter_names'] = array();
$GLOBALS['chapter_names'][] = $row -> CHAPTER_NAME;


print_r($GLOBALS);

Upvotes: 1

alex
alex

Reputation: 490333

That should work.

$GLOBALS["chapter_names"] = array();

$row = new StdClass;

$row->CHAPTER_NAME = 'test';

$i = 0;

$GLOBALS["chapter_names"][$i] = $row -> CHAPTER_NAME;

var_dump($GLOBALS);

Amongst other things, the value is displayed...

["chapter_names"]=>
  array(1) {
    [0]=>
    string(4) "test"

However, as you are probably aware, variables should only have as much scope as required, to prevent clashes and possible problems. Therefore, global variables should be avoided in most scenarios.

Upvotes: 0

Related Questions