Array declared outside function, used in function, no go

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
Hermes122
Forum Newbie
Posts: 1
Joined: Wed Oct 21, 2009 8:22 pm

Array declared outside function, used in function, no go

Post 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();
?>
 
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

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

Post 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);
?>
Post Reply