Search code examples
phpvariablesvariable-variables

Obtaining a variable value when echoing its name inside a for loop


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


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];
    }