iicaptain
iicaptain

Reputation: 1195

A variable as part of the name of a variable in PHP

Here are the variables:

$fake= 'cool';
$fake1 = 'not cool';
$hope= '1';

The idea is to combine $fake and the $hope to create the variable $fake1. The idea is that if the $hope variable was randomized it could generate a random variable: $fake1, $fake2, $fake3, etc. Right now I either get an error or just the values of $fake and $hope next to each other not the new variable.

Upvotes: 0

Views: 123

Answers (3)

Baba
Baba

Reputation: 95161

You can try

$fake = array(
        "fake1" => "Cool",
        "fake2" => "Bad",
        "fake3" => "Fish",
        "fake4" => "Next",
        "fake5" => "Wow");

list($a, $b) = array_rand($fake, 2);
echo $fake[$a] . " " . $fake[$b]; // This would always change

Upvotes: 1

DaOgre
DaOgre

Reputation: 2100

Ben's comment above does probably exactly what you're looking for, but if you're in PHP5 you can also do something like:

 $varname = $fake . $hope;
 $$varname = "horray";

Upvotes: 1

Brendan Long
Brendan Long

Reputation: 54312

You should use an "array" for this:

$list = array('cool', 'not cool');
$random_item = array_rand($list);

Using variable-named variables is always messy and this is exactly what arrays are for.

Upvotes: 3

Related Questions