1

This is my php code:

$text1 = "text 1";
$text2 = "text 2";
$text3 = "text 3";
  for($i=1; $i<=3; $i++){

     echo "<script>alert('$text1');</script>";
  }

In here I want to create $text1, $text2 ... variables automatically using for but when I replace the $text1 with $text.$i php fetchs $text + $i me individually. How can I do this?

3
  • 6
    use arrays instead. Commented Feb 2, 2017 at 14:50
  • I know it but I don't want to use array. Commented Feb 2, 2017 at 14:58
  • Then you don't know what you're doing. Commented Feb 2, 2017 at 15:41

3 Answers 3

2

You can use ${'text'.$i} to print them in the for.

Sign up to request clarification or add additional context in comments.

Comments

0

You should use an array

$text[0] = "text 0";
$text[1] = "text 1";
$text[2] = "text 2";  

foreach ($text as $key => $value){

    echo "<script>alert('".  $value. "');</script>";
}

or use the { 'string' . $cnt } construct

Comments

0

this is probably not the best way to do it, i would suggest using an Array.

<?php
    $array = array(
        'text1' => "Text 1",
        'text2' => "Text 2",
        'text3' => "Text 3",
    )

    for($array AS $key => $value) {
        echo "<script>alert('$value');</script>";
    }
?>

However, in PHP it is possible to call a variable inside a string. So you could do something like that.

<?php
    $text1 = "text 1";
    $text2 = "text 2";
    $text3 = "text 3";
    for($i = 1; $i <= 3 ; $i ++) {
         $value = "text" . $i;
         echo "<script>alert(" . $$value . ");</script>";
    }
?>

Hope it helps !

  • Nic

2 Comments

I know it but I don't want to use array.
@FoeMartist Then you can use the second method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.