Jump to content

Recommended Posts

Hi,

 

Sorry if this seems simple but I am going a bit mad. I have done this a thousand of times before and for some reason today it is not working.

 

I just want to join two variables together like $item_number$i

 

But for some reason it just wont work it only ever prints out the value of $i

 

I swear the following used to work in PHP 4

 

I am using php 5

 

$item_number1 = "foo";
$item_number2 = "bar";

$i = 1;
while($i <= 2) {
echo "$item_number$i <br />";
$i++;
}

 

The above code just prints out:

 

1

2

 

Please can someone help, I am going insane :(

 

Thanks

I would suggest using an associative indexed array instead, but here is how you would achieve that:

 

$item_number1 = "foo";
$item_number2 = "bar";

$i = 1;
while($i <= 2) {
   echo ${$item_number . $i} . "<br />";
   $i++;
}

 

Should do what you want. An array would be better a quicker, however. As an FYI.

Hi premiso

 

Thanks for the quick reply, for some reason the following code doesn't print out anything :(

 

$item_number1 = "foo";
$item_number2 = "bar";

$i = 1;
while($i <= 2) {
   echo ${$item_number . $i} . "<br />";
   $i++;
}

 

Have you any ideas?

 

Can I ask is this a change in PHP 5 that has stopped the usual "$var$i" from working as its been bugging me all day.

Thanks kenrbnsn that works perfectly.

 

Out of interest I have decided to use the array method as previously mentioned, this is a faster better technique?

 

$item_number[1] = "foo";
$item_number[2] = "bar";

$i = 1;
while($i <= 2) {
   echo $item_number[$i] . "<br />";
   $i++;
}

If you're going to use an array, I would suggest using either a for loop

<?php
$item_number = array(1=>'foo',2=>'bar');
for ($i=1;$i<3;++$i) {
   echo $item_number[$i] . "<br />\n";
}?>

or a foreach loop

<?php
$item_number = array(1=>'foo',2=>'bar');
foreach ($item_number as $val) {
   echo $val . "<br />\n";
}
?>

 

Ken

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.