Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String concantenation error 1

Status
Not open for further replies.

maharg

Technical User
Mar 21, 2002
184
Hi

I'm new to PHP and can't seem to get my syntax right here.

This little test code should print out as ....

1,2,3,4,5,6,Graham,
2,4,6,8,10,12,Edward,
10,20,30,40,50,60,James,
41,42,43,44,45,46,Gordon,

But it doesnt.

My error is in the line print_r($person$n[$i]);
to do with how I'm concantenating $person and $n

Can anyone help me find a solution?

Thanks in advance!!

Graham

Code:
<html>
<body>
   
<?php

$person1 = array(1,2,3,4,5,6, "Graham");
$person2 = array(2,4,6,8,10,12, "Edward");
$person3 = array(10,20,30,40,50,60, "James");
$person4 = array(41,42,43,44,45,46, "Gordon");

$n=1;
while($n<=4){

       $i=0;
       while($i<=6)
       {
       print_r($person$n[$i]);
       echo ",";
       $i++;
        }
       
echo "<br />";
$n++;}
?>

</body>
</html>

 
To join two strings use the period "."

In your case, you should simplify your code to use a multi-dimensioned array and the implode function to format your output.
Code:
<?php

$people = array(array(1,2,3,4,5,6, "Graham"),
          array(2,4,6,8,10,12, "Edward"),
          array(10,20,30,40,50,60, "James"),
          array(41,42,43,44,45,46, "Gordon"));

for ($n=0;$n<count($people);$n++)
       echo implode(',',$people[$n]).",<br />\n";
?>

Ken
 
Hi Ken,

Wow, that's more efficient, thanks!

I tried the "." period string addition in my example but it wouldn't work. It works fine for other strings, and I use it a lot.

But, keeping the basic structure of my code example, how would you combine $person and $n so that the code understands ...
$person1 $person2 etc?

Just so I can understand where my syntax was wrong in that line, keeping all else the same.

I'm off to read about multidimensioned arrays now...

Thanks again Ken
 
What you want to do is create a variable with the value of "person1", "person2", etc. and then use that value as your variable. Look up variable variables on
The following code
Code:
<?
$person1 = array(1,2,3);
$person2 = array(4,5,6);
$per = 'person';
for ($i=1;$i<3;$i++) {
    $perx = $per .$i;
    echo $perx,': ' ,implode(',',$$perx),"\n"; }
?>
will print
Code:
person1: 1,2,3
person2: 4,5,6
Basically, two '$' preceding a variable name say take the value of the variable and used it as a variable name.

Ken
 
Ken, that's great, thanks for everything.
Much appreciated.

Best regards,

Graham
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top