Click to See Complete Forum and Search --> : Array Help


Joseph Witchard
08-01-2008, 11:07 PM
Can you declare PHP variables and then store them in an array? I'm trying to create a script that echos random HTML code every time the page loads, but I wanted to check this before I started. My code will show you what I'm hoping to achieve:

<?php

$var1 = include("file1.html");
$var2 = include("file2.html");
$var3 = include("file3.html");
$var4 = include("file4.html");

$array = array($var1, $var2, $var3, $var4);)

// somewhere in the HTML part of the page

echo $array[rand(0, 3)];

?>

Jick
08-02-2008, 12:20 AM
I don't believe you can use include like that. Instead, I think you need to read in the contents of those files and put them into the variables. Then those variables can be put into your array.

Something like this should work:<?php
$var1 = file_get_contents("file1.html");
$var2 = file_get_contents("file2.html");
$var3 = file_get_contents("file3.html");
$var4 = file_get_contents("file4.html");

$array = array($var1, $var2, $var3, $var4);)

// somewhere in the HTML part of the page
echo $array[rand(0, 3)];
?>Be careful though because some older versions of PHP have issues with using URLs to get the file. It's safer to use absolute paths if you can.

Hope that helps. :)

NogDog
08-02-2008, 08:45 AM
More efficient would be:

<?php

$includeFiles = array(
"file1.html",
"file2.html",
"file3.html",
"file4.html"
);
include $includeFiles[rand(0, count($includeFiles) - 1];

Joseph Witchard
08-06-2008, 09:15 PM
Thanks!