tags:

views:

61

answers:

2
$i = 'i';
$arr = array('hi' => 'test');
echo "$arr[h$i]";exit();

What's the right version to do it without {}?

Say,I know can do it with "{$arr['h' . $i]}"

EDIT

1.inside "" 2.with operation like ".",i.e,['h' . $i] 3.without {}

A: 
$index = 'h' + $i;
echo $arr[$index];
exit;

?

meder
I also know this version.I mean how to do operations without {}?
Shore
I don't see a single "{" anywhere in meder's answer, do you?
timdev
But there are no operations like "."
Shore
Where are there no operations like "."? You want a solution that doesn't use "." and doesn't use {}??? Then see my answer. You want to do it all in one line? I want a pony.
timdev
lol.Why do you want a pony?to do what with ?
Shore
That's short hand for "too bad, you can't have what you want". The point being, I'm not gonna get a pony, and you're not gonna get to be able to write echo "$array[pre$fix]"; and have it work.
timdev
+1  A: 

If you don't want {}, you'll need to do it this silly way:

$idx = "h$i";
echo "$arr[$idx]";exit();

Of course, you could also just do

$i = 'i';
$arr = array('hi'=>'test');
echo $arr["h$i"]; exit();

But I think maybe you oversimplified things for the purposes of your question.

timdev
+1 for "But I think maybe you oversimplified things for the purposes of your question." I'm waiting for the "What are you trying to accomplish?" answer.
Chris Lutz
Yeah, exactly. It seems like Shore is just angry that the parser won't parse what he thinks it should.
timdev
Oh guys,I like doing things inside "",and until recently I come to know that I can access array value without {},but the key can't be a combined one?I ask this question to ensure or deny this.
Shore
Yeah, the parser will choke on that much of a shortcut. Your only options are to use {}, or get the key into a single variable.
timdev
Can you prove it or not?
Shore
You already proved it. Try running your code. What happens? A parse error, that's what.
timdev
I might have done it in a wrong way,but doesn't mean there are no way to do it.
Shore
it's just language syntax. You can do what you want to do, in several ways, which you already know. As far as I can tell, your question is just "why can't I do it this way", and the answer is because it's invalid syntax according to the php parser.
timdev