0

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.

4
  • How exactly do you expect to get from 'cool' and '1' to $fake1? Commented Oct 10, 2012 at 20:58
  • 2
    How about $fake{$hope}="coooooler!"; ? Commented Oct 10, 2012 at 20:58
  • Generating random variable names does not sound like a good idea. I would recommend an array and array_rand(). Commented Oct 10, 2012 at 20:59
  • 1
    Yes, noobs inquiring about var varnames usually means they skipped the chapter on arrays. Commented Oct 10, 2012 at 21:09

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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";

4 Comments

The OP asked how to have a variable as part of a variable name. I agree, arrays are better.
Solved it using DaOgre's solution modified. code $varname = "fake" . $hope; echo $$varname; code Thanks everyone for your help. I really appreciate it.
Variable variables are the direct way to hell. Use arrays.
@user1736174 Seriously, you don't want to do this. Just because you can doesn't mean you should.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.