joon1
September 25, 2020, 1:46pm
1
$herName='Mary';
$hisName='Tom';
$sex='her';
echo ${$sex. 'Name'};
The code above produces “Mary”.
And the code below procudes “Tom”.
$herName='Mary';
$hisName='Tom';
$sex='his';
echo ${$sex. 'Name'};
However, the code below doesn’t produces “Jane”.
$her['Name']='Jane';
$his['Name']='Jack';
$sex='her';
echo ${$sex. "['Name']"};
Can I modify the code above to produce “Jane” with you help?
Surely it needs to be
<?php
$her['Name']='Jane';
$his['Name']='Jack';
$sex='her';
echo ${$sex}['Name'];
I would HIGHLY recommend against the use of Variable Variables.
Not something I use, it all seems quite complicated to follow, especially months after you wrote it. It would perhaps be interesting to know why the OP is looking at this. Hopefully just as a learning experience.
2 Likes
rpkamp
September 26, 2020, 10:05am
6
I’d probably do it like this:-
$names = [
'her' => 'Jane',
'his' => 'Jack',
];
$sex = 'her';
echo $names[$sex]; // Jane
(be aware this can result to an Undefined index
warning if you’re referencing a key that is not in $names
)
1 Like
Guess what happens when you add another her or his .
The OPs original arrays won’t support more than one entry without some modification, either.
Yeah, the idea is flawed from the start. No idea what the OP is really trying to do. Hopefully just trying to learn.
system
Closed
December 26, 2020, 11:29pm
11
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.