Forum Moderators: coopster
Problem:
I have main.php call menu.php using the include() function.
How do I pass an array created in menu.php to main.php?
I've tried using sessions in all sorts of configurations and I can't seem to get it right. The most frequent error message complains that the variable is undefined. I'm starting to suspect that this can't be done with sessions.
Am I right? Any suggestions on how to pass the array?
Any comment at all would be appreciated.
<?php
// menu.php
$array1 = array(2,4,6,8);
function func() {
$vbl = array(1,3,5,7);
return($vbl);
} // end func()
?>
<?php
// main.php
include "menu.php";
echo "<html><head></head><body>\n";
echo 'array1:<br />';
for($i = 0, $u = count($array1);$i < $u;$i++)
echo $array1[$i] . '<br />';
$array2 = func();
echo 'array2:<br />';
for($i = 0, $u = count($array2);$i < $u;$i++)
echo $array2[$i] . '<br />';
echo "</body></html>\n";
?>
D'OH!
The call to the array has to be within the same <?php...?> tags as the include() function!
I was trying to do something like this:
<!-- START MAIN.PHP -->
some HTML...
<?php include('menu.php');?>
some more HTML...
<?php
echo "$array[1]"; // echo array element created in menu.php
?>
some more HTML...
<!-- END MAIN.PHP -->
Dang! 5 hours on that! (sheesh... live and learn...)
One million thank yous, cameraman!
That should be:
<?php
echo "{$array[1]}"; // echo array element created in menu.php
?>
keeping it inside quotes, or
<?php
echo $array[1]; // echo array element created in menu.php
?>
The last one is preferred when possible/convenient.
This is what I was intially attempting:
<?php echo "{$array['test']}";?>
<?php include('menu.php');?>
...which didn't work. So it suddenly hit me that the array can't be accessed until it's actually created so I switched the two...
<?php include('menu.php');?>
<?php echo "{$array['test']}";?>
...and now this works.
Does that make sense? Or have I still got it wrong?