Question

I'm learning and I've been stuck for so long now with something I believe is too simple, sorry if I'm right. Please help me to evolve, here's my question:

I have coming from a form:

  $text1 = $_POST['TEXT1'];
  $text2 = $_POST['TEXT2'];
  $text3 = $_POST['TEXT3'];

Now I do:

 for ($n = 1; $n <= 3; $n++) {
 echo "Number " .$n. " is: " .$text.$n;
}

This is printing:

Number 1 is: 1

Number 2 is: 2

Number 3 is: 3

When what I need is:

Number 1 is: value contained in $text1

Number 2 is: value contained in $text2

Number 3 is: value contained in $text3

How can achieve what I need?

Thanks a lot

Was it helpful?

Solution

You could put your values into an array:

$texts = array($_POST['TEXT1'], $_POST['TEXT2'], $_POST['TEXT3']);

for ($n = 0; $n < count($texts); $n++) {
    echo "Number " . ($n+1) . " is: " . $texts[$n];
}

OTHER TIPS

for ($n = 1; $n <= 3; $n++) {
 $var = "text".$n;
 echo "Number " .$n. " is: " .$$var;
}

but it would be nicer if you save the POST data in an array

you can do it like this:

$text = array();
$text[] = $_POST["TEXT1"];
$text[] = $_POST["TEXT2"];
$text[] = $_POST["TEXT3"];

then you can do it like that:

for ($n = 1; $n <= count($text); $n++) {
 echo "Number " .$n. " is: " .$text[$n-1];
}

Use this:

for ($n = 1; $n <= 3; $n++) {
    echo "Number " .$n. " is: " . ${'text'.$n};
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top