Problem returning array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
HiddenS3crets
Forum Contributor
Posts: 119
Joined: Fri Apr 22, 2005 12:23 pm
Location: USA

Problem returning array

Post 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?
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post 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
HiddenS3crets
Forum Contributor
Posts: 119
Joined: Fri Apr 22, 2005 12:23 pm
Location: USA

Post by HiddenS3crets »

thanks, adding global fixed it :D
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

a much cleaner approach to this is to simply pass the array to the function.

Code: Select all

function getSection1($sections) {
...
Post Reply