Page 1 of 1

Problem returning array

Posted: Sat Sep 30, 2006 3:47 pm
by HiddenS3crets
I have an array declared like this:

Code: Select all

$sections = array('Section 1' => array('something', 'something'), 'Section 2' => array('something', 'something'), 'Section 3' => array('something', 'something'));
Then I use three separate functions to get the 3 keys

Code: Select all

function getSection1() {
 return $sections['Section 1'];
}

function getSection2() {
 return $sections['Section 2'];
}

function getSection3() {
 return $sections['Section 3'];
}
I call these from another file as:

Code: Select all

$sec1 = getSection1();
$sec2 = getSection2();
$sec3 = getSection3();
Now, these should be returning arrays, thus $sec1, $sec2 and $sec3 will hold arrays. The problem is that it's not doing what it should...

but if I do this:

Code: Select all

$sec1 = $sections['Section 1'];
$sec2 = $sections['Section 2'];
$sec3 = $sections['Section 3'];
And this assigns arrays to the $sec# variables.

Why doesn't it work if I return an array from functions, but it works if I access the $sections array directly?

Posted: Sat Sep 30, 2006 3:51 pm
by n00b Saibot
you know something called variable scope? I suggest read the manual on php.net site.

inside of functions, your array variable is not accessible.. so you have to do following...

Code: Select all

function getSection1() { 
 global $sections;
 return $sections['Section 1']; 
} 

function getSection2() { 
 global $sections;
 return $sections['Section 2']; 
} 

function getSection3() { 
 global $sections;
 return $sections['Section 3']; 
}
IMO you are much better off using direct array notation to access vars

Posted: Sat Sep 30, 2006 3:54 pm
by HiddenS3crets
thanks, adding global fixed it :D

Posted: Sat Sep 30, 2006 5:25 pm
by John Cartwright
a much cleaner approach to this is to simply pass the array to the function.

Code: Select all

function getSection1($sections) {
...