2

Using for loop in PHP can we have numbers associate with a variable name?

ex:

$name1="hi";
$name2="khj";

for($i=0;$i<=2;$i++)
{
echo ..
}

How can we print $name1 and $name2 using for loop?

Thanks!

5 Answers 5

5

Yes this is called variable interpolation.

$name1="hi";
$name2="khj";

for($i=1;$i<=2;$i++) {
    $var = 'name' . $i;
    echo $$var;
}

Note: There are multiple syntaxes for variable interpolation in PHP. Also, I modified your loop to start at 1.

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

Comments

5
    for($i = 1; $i <= 2; $i++)
    {   
        echo $name{$i};
    }

It would be way easier to put it in an array though, that's what we have them for.

    $names = array();
    $names[1] = 'A';
    $names[2] = 'B';

    foreach($names as $name)
    {
        echo $name; 
    }

Comments

3

put this in the for loop:

echo ${'name'.$i}."\n";

Comments

2

Better to use something like:-

$names[] = $name1;
$names[] = $name2;

foreach($names as $name){
    echo $name;
}

Comments

0

This print the name1 and name2 .And i value must be start from 1

      for($i=1;$i<=2;$i++)
       {
         echo ${'name'.$i}."<br>";
        }

4 Comments

This is not what the user is asking.
Don't think so. Test it yourself. Your output, as you noted, is name1 and name2.
If your answer "matches" with everybody else, why bother writing a new answer. Just upvote the one you think is the best answer.
sorry every body done wrong in over look.Now i edited my answer

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.