views:

429

answers:

6

look at this simple script please

$c1 = $_GET[c1];
$c2 = $_GET[c2];
$c3 = $_GET[c3];
$c4 = $_GET[c4];
$c5 = $_GET[c5];
for($i = 1;$i <=5;$i++)
{
    echo $c{$i};//or something else here :/
}

how can i print tha values of variables?

Thanks

A: 

Perhaps PHP variable variables is what you are looking for.

$i = "c1";
print $$i;

I'll leave it to you to figure out how to construct correct values for 'i'.

Gian
Can I ask why this was downvoted?
Gian
+4  A: 

You can see on php.net some good examples in the variable page. Read that and take a look at the examples.

Also, below is your piece of code fixed so it can work:

<?php

$c1 = $_GET[c1];
$c2 = $_GET[c2];
$c3 = $_GET[c3];
$c4 = $_GET[c4];
$c5 = $_GET[c5];
for($i = 1;$i <=5;$i++)
{
    echo ${"c".$i};
}
Bogdan Constantinescu
This is not a good thing to advise the guy to do. This is a case where arrays are the most appropriate answer; why tell him to use variable variables?
Hammerite
He wanted variable variables (probably because in `$c1`, `$c2` etc checks the $_GET contents. If he would have asked for other solutions, I would suggest others, but it seems to me this questions is about **variable variables**.
Bogdan Constantinescu
This answer is more correct, but recommending arrays is better. In cases like these, I feel that the best answers are a merging of yours and @Kieren Johnstone: they offer the solution to the question at hand, but also make a point of saying that it's really not good practice. Regardless, +1 to you both xP
Matchu
+3  A: 

You should use an array rather than individual variables.

For reference:

http://php.net/manual/en/language.types.array.php

Kieren Johnstone
A: 

This should work..

 foreach($_GET as $id => $value){
      echo $value;
 }

even though this prints out every $_GET.

Jose Vega
+3  A: 

If these values are closely related, consider changing their name attribute in your HTML/form.

HTML:

<form>
    <input type="text" name="c[]" />
    <input type="text" name="c[]" />
    ...
</form>

PHP:

<?php

    if(!empty($_GET['c'])) {
        foreach($_GET['c'] as $c) {
            echo $c;
        }
    }

?>
Daniel
+1  A: 

Here's a better way of doing it, using Arrays, rather than individual variables, which works easier and more efficiently.

<?php
$array['c1'] = $_GET['c1'];
$array['c2'] = $_GET['c2'];
$array['c3'] = $_GET['c3'];
$array['c4'] = $_GET['c4'];
$array['c5'] = $_GET['c5'];
for ($i=1; $i>=5; $i++) {
    echo $array['c' . $i];
}
?>
Matthew Else