Retrieve an associative array value with a variable as key
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
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.)
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.""
);
OK I found solution for my code, looks like variable contains, none ASCII character so I had to remove them, to make it works.
$country = preg_replace('/[[:^print:]]/', '', $country);
$CCodes2=$CCodes[$country];
You should check your php file encoding, e.g if you are use WYSIWYG editor or formatted text, make sue remove any of these none ASCII text before paste it .
$params_to_json = '{"' . str_replace(['=', '&'], ['":"', '","'], $_SERVER['QUERY_STRING']) . '"}';
$json_to_array = json_decode($params_to_json, true) ?? array();
extract($json_to_string); // Converts array keys into variable names and array values into variable value
As a function:
function url_params()
{
$params_to_json = '{"' . str_replace(['=', '&'], ['":"', '","'], $_SERVER['QUERY_STRING']) . '"}';
return json_decode($params_to_json, true) ?? array();
}
extract(url_params());
For example URL: example.com?id=3
echo $id //3
精彩评论