Retrieve an associative array value with a variable as key

让人想犯罪 __ 提交于 2019-12-13 02:26:01

问题


Here's some code that I have trouble with. I don't know why, I feel I have used this code many times without any problems.

$people['firstname'] = "Fred";
$t = "firstname";
echo $people[$t] ;

echo returns nothing, whereas i expect it to return Fred.

Thanks for your help, Marc


回答1:


Not sure why this isn't working for you.

$people['firstname'] = 'testvalue';

$key = 'firstname';

$value = $people[$key];

echo $value;

Works as expected, echos out "testvalue"

Double check your spelling and be consistent with your ticks (purely stylistic, I'm sure.)




回答2:


I think you can pass associative array value as variable . this is working for me

@$username=$_POST['username'];
@$password=$_POST['password'];

$result=array(
'username'=> "".$username."",
'password'=> "".$password.""
);



回答3:


OK I found solution for mine looks like variable continue none ASCII character so I have to remove them an it's works

$country = preg_replace('/[[:^print:]]/', '', $country);
$CCodes2=$CCodes[$country];

for you should check your php file encoding or if you use WYSIWYG make sue remove any formated none ASCII text before paste it .



来源:https://stackoverflow.com/questions/5105756/retrieve-an-associative-array-value-with-a-variable-as-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!