views:

446

answers:

3

Hey,

Say I am echoing a large amount of variables in PHP and I wont to make it simple how do i do this? Currently my code is as follows but it is very tedious work to write out all the different variable names.

echo $variable1;
echo $variable2;
echo $variable3;
echo $variable4;
echo $variable5;

You will notice the variable name is the same except for an incrementing number at the end. How would I write a script that prints echo $variable; so many times and adds an incrementing number at the end to save me writing out multiple variable names and just paste one script multiple times.?

Thanks, Stanni

+7  A: 

You could use Variable variables:

for($x = 1; $x <= 5; $x++) {
    print ${"variable".$x};
}

However, whatever it is you're doing there is almost certainly a better way: probably using Arrays.

Paolo Bergantino
Yup. php likes arrays, and makes them easy.
le dorfier
+2  A: 

Use dynamic variable names:

for($i=1; $i < 6; $i++) echo ${'variable'.$i}
vartec
you concatenate with . in PHP
Paolo Bergantino
+3  A: 

I second Paolo Bergantino. If you can use an array that would be better. If you don't how to do that, here you go:

Instead of making variables like:

$var1='foo';
$var2='bar'; 
$var3='awesome';

... etc... you can make a singe variable called an array like this:

$my_array = array('foo','bar','awesome');

Just so you know, in an array, the first element is the 0th element (not the 1st). So, in order to echo out 'foo' and 'bar' you could do:

echo $my_array[0]; // echoes 'foo'
echo $my_array[1]; // echoes 'bar'

But, the real benefits of putting value in an array instead of a bunch of variables is that you can loop over the array like this:

foreach($my_array as $item) {
    echo $item;
}

And that's it. So, no matter how many items you have in your array it will only take those three lines to print them out. Good luck you with learning PHP!

KyleFarris