Page 1 of 1

Array declared outside function, used in function, no go

Posted: Wed Oct 21, 2009 8:32 pm
by Hermes122
Probably an easy question, but why won't this work:

Code: Select all

 
<?php
$testArray = array('foo','bar','baz');
 
echo $testArray[0];
 
echo "<br /><br />";
 
function testTheArray() { echo "Running test: ".$testArray[0]; }
 
testTheArray();
?>
 
Actually as I was writing this I found the answer: http://stackoverflow.com/questions/1181 ... rray-error
...but I'll post this up anyway (may help someone):

Fixed code:

Code: Select all

 
<?php
$testArray = array('foo','bar','baz');
 
echo $testArray[0];
 
echo "<br /><br />";
 
function testTheArray() { global $testArray; echo "Running test: ".$testArray[0]; }
 
testTheArray();
?>
 

Re: Array declared outside function, used in function, no go

Posted: Wed Oct 21, 2009 11:24 pm
by John Cartwright
Using globals is hackish and can be difficult to properly maintain the code. Your best bet is to pass the value to the function itself, i.e.,

Code: Select all

<?php
$testArray = array('foo','bar','baz');
 
echo $testArray[0];
 
echo "<br /><br />";
 
function testTheArray($testArray) { echo "Running test: ".$testArray[0]; }
 
testTheArray($testArray);
?>