Connecting Tech Pros Worldwide Forums | Help | Site Map

"<td><input name='".$i-2."'

aa
Guest
 
Posts: n/a
#1: Jul 17 '05
I am traing to output the following HTML string from PHP:
"<td><input name='".$i-2."' size='2' type='text'
onBlur='myfunction(".$i-2.")'></td>"
But it somehow mistreats $i-2. PHP does not throw any errors but the
browser renders the table incorrectly.
I got round this by introducing another variable
j=i-2 and using it in place of i-2
It works. However I am interested to understand why is does not work with
i-1. Any comments?


Michael Fesser
Guest
 
Posts: n/a
#2: Jul 17 '05

re: "<td><input name='".$i-2."'


.oO(aa)
[color=blue]
>I am traing to output the following HTML string from PHP:
>"<td><input name='".$i-2."' size='2' type='text'
>onBlur='myfunction(".$i-2.")'></td>"
>But it somehow mistreats $i-2. PHP does not throw any errors but the
>browser renders the table incorrectly.[/color]

I get a parse error, but even without that the above would not do what
you want. In fact what you are trying do to is to print a difference of
these three strings:

"<td><input name='".$i
2."' size='2' type='text' onBlur='myfunction(".$i
2.")'></td>"
[color=blue]
>I got round this by introducing another variable
>j=i-2 and using it in place of i-2
>It works.[/color]

There are some other ways to solve that issue:

1) Use parentheses around the $i-2, e.g.

print "<td><input name='".($i-2)."' size='2' ...";

2) Use printf() and a format string with placeholders, which are then
replaced with $i-2. See the manual on sprintf() for details.

Micha
aa
Guest
 
Posts: n/a
#3: Jul 17 '05

re: "<td><input name='".$i-2."'


Thanks, Micha
It never occured to me that concatination could have hight priority than
arithmetic operations.



Erwin Moller
Guest
 
Posts: n/a
#4: Jul 17 '05

re: "<td><input name='".$i-2."'


aa wrote:
[color=blue]
> I am traing to output the following HTML string from PHP:
> "<td><input name='".$i-2."' size='2' type='text'
> onBlur='myfunction(".$i-2.")'></td>"
> But it somehow mistreats $i-2. PHP does not throw any errors but the
> browser renders the table incorrectly.
> I got round this by introducing another variable
> j=i-2 and using it in place of i-2
> It works. However I am interested to understand why is does not work with
> i-1. Any comments?[/color]

Hi,

I noticed that problem too.
I guess there is a very valid reason why it happens. :-)

Solve it by using ()
so:
$i=1;
echo "testing i+1=".$i+1; // gives 1

but

echo "testing i+1=".($i+1); // gives 2


Possible reason (as a guru to be sure. :P)
I expect PHP interprets the line as:
$result = (print "i+1=".$i) + 1;
// result contains 2 now!

where:

$result = (print "i+1=".($i + 1);
// result contains 1 now!


Regards,
Erwin Moller
Closed Thread