-1

Im a New programmer I new a few help, I have a code where I need to call many different variables like this:

$Variable1="red"
$Variable2="blue"
$Variable3="yellow"

How can I call my variable as a variable like this:

$number = 1;
$color=$variable.$number;

Or how can u do that, thank you.

2 Answers2

2

Have you tried array

$variables = array(0, 'red', 'blue', 'yellow');
$number = 1;
$color = $variables[$number];
echo $color;

Using as @frymaster's answer:

$Variable1="red";
$Variable2="blue";
$Variable3="yellow";

$number = 2;

$colour = "Variable{$number}";
print $$colour;

Or using eval() function - not recommend to use

$variable1 = 'red';
$variable2 = 'blue';
$variable3 = 'yellow';
$number = 1;
eval("echo $variable" . $number . ";");
Thi Tran
  • 681
  • 5
  • 11
0

thi tran's answer is, really, the best solution. if you're going to use numbers to differentiate elements of data in a set... well, that's what the array was designed to do!

having said that, you can make a 'variable variable' and use that, if you really want to. but the array is a smarter choice.

here's the variable variable $colour

<?php

$Variable1="red";
$Variable2="blue";
$Variable3="yellow";

$number = 2;

$colour = "Variable{$number}";
print $$colour;
frymaster
  • 664
  • 7
  • 12
  • yes, i forget this way, i have just edited my answer, thanks – Thi Tran Jul 25 '15 at 00:19
  • Yes, but i would not recommend using such code, years ago I ran across this and when WtH, thought it was a typo. To me code should be clear and concise as to its purpose. Variable Variables, while valid are best left in the dustbin of PHP4 if you ask me. – ArtisticPhoenix Jul 25 '15 at 02:21
  • oh, i fully agree! variable variables are just asking for trouble imho. again, thi tran's original suggestion to use variables is far and away the best approach. i only added this because it explicitly answered the op's question. – frymaster Jul 25 '15 at 02:55