Question

I'm learning php on a very basic level and need som assistance.

I want to echo variables from one file to another. I'll try to reproduce:

folder/file1.php file1.php contains 3 different php scripts:

php $var1 = "Hello"
php $var2 = "Goodbye"
php $var3 = "Nice"

And i want to echo one of the three variables randomly (scrambled) on various pages.

I use this now:

php include 'folder/file1.php'; echo get_($var1);

But it only displays the $var1 text.

Was it helpful?

Solution

How about:

<?php

$var1 = "Hello";
$var2 = "Goodbye";
$var3 = "Nice";

$i = rand(1, 3);
echo ${"var" . $i}

?>

At run time ${"var" . $i} is calculated to be $var1, $var2 or $var3.

Using php rand and dynamically created variable will let you do it. You can just continue to include your other files above this script and ensure the variables are named in a static way as shown above and it will work.

Example: Here (click edit then ideoneit)

OTHER TIPS

put those vars in an array, and randomly select an element from the array:

$myItems = array("hello","goodbye","lovely");
echo $myItems[rand(0,2)];

http://us2.php.net/rand

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top