1

I know what i have implemented here is wrong i want it to do it correctly that is why asking help here.Don't know whether this is possible or not.

<?php
$test1="hello";
$test2="how";
$test3="are";
for($i=1;$i<=3;$i++)
{
    echo $test.$i;
}
?>

When i run this i should get hello how are .i know string concatenation same thing i want to do it for variable also.Is this Possible, if possible by this i can easily access all those variable. Any help?

6
  • 4
    Duplicate of a million other questions, see variable variables (or better yet, store your values in an array). Commented Sep 10, 2013 at 13:32
  • 2
    Wouldn't array be better? $test[1]='hello';$test[2]='how';$test[3]='are'; foreach($test as $val) { echo $val; } Commented Sep 10, 2013 at 13:32
  • no only in for loop i would like to do, Thanks Commented Sep 10, 2013 at 13:34
  • 1
    Just a question, but why would you like to do this? With all do respect, but this programming logic seems like a rather bad idea to me. If you could provide more framework of what you try to achieve, someone can advise you with code for a better alternative. Commented Sep 10, 2013 at 13:40
  • @KimGysen agree with you, seems like a bad OOP, but I've just learnt that it's actually possible to do such thing LOL! Commented Sep 10, 2013 at 13:45

3 Answers 3

3

Try with following syntax:

echo ${'test'.$i};
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect.can i use more variable like this? @hsz
If you put it in your loop, $i will change and call next variables. Is it that what did you mean ?
0

I guess what you're looking for is the "array". You can use arrays in PHP like this:

$test = array('hello', 'how', 'are');
$len = count($test);
for($i=0; $i<$len; $i++) {
   echo $test[$i];
}

5 Comments

i don't want array in this case, Thanks for alternatives.this things will give us more knowledge
@sun then I guess hsz has your answer.. which is also new to me! +1 for your question! I didn't know that this is possible in PHP!
Thanks for you appreciation.if possible can you clarify me some doubts in oop so that i can learn it well. @evilReiko
@sun no problem, what do you need to know about OOP?
if possible any other chatting kind of interaction(site).so that we can discuss more @evilReiko
-2

Try this:

for($i = 1; $i < 4; $i++){
    echo $test{$i};
}

Comments

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.