Variable inside a variable with braket value

$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

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.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.