Accessing arrays accross php pages

Associate
Joined
19 Jun 2006
Posts
162
Location
Swansea, Wales
Hi,

I have an array that I want to use in a number of pages so i wrote it in a file arrays.php then included this page on my other pages. I wrote the array then wrote a function to return it...

Code:
<?php

		$fields = array	(	0=>"Accept",
								1=>"Accept-Encoding",
								2=>"Accept-Language",
								3=>"Alert-Info",
								4=>"Allow",
	                 			
function getFields() {
	
	return fields;
	
}

I was hoping to then just call the function from other pages to get the array...

Code:
$array = getFields();

... but it didn't work out that way! Where am I going wrong?
 
Code:
function getFields() {
        global $fields;
	
	return $fields;
	
}

That would work, because it is a function it does not use any variables from out side the function unless you global them.

Clarkey is right however, you do not need the function. You just type use the var name $fields from another file.

If you are using the $fields variable from inside a function, then global $fields; at the top of the function too :-)
 
Globals are nasty; a more viable equivalent would be:

PHP:
<?php

$fields = array(
	0 => 'Accept',
	1 => 'Accept-Encoding',
	2 => 'Accept-Language',
	3 => 'Alert-Info',
	4 => 'Allow',
);
	                 			
function getFields($arr)
{
	return $arr;
}

$x = getFields($fields);

?>

Taking the array as a function argument then returning it.

But as you can see, this is pointless - as Clarkey stated.
 
OK, cheers guys. I have been writing Java for the last 8 weeks and so my mind set is to get everything with a function! ;)
 
Back
Top Bottom