Marco
Marco

Reputation: 37

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

Upvotes: 1

Views: 20007

Answers (4)

Salem
Salem

Reputation: 774

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 .

Upvotes: 1

gadolf
gadolf

Reputation: 1065

$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

Upvotes: 0

Tanver
Tanver

Reputation: 11

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.""
);

Upvotes: 1

Ian P
Ian P

Reputation: 12993

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.)

Upvotes: 2

Related Questions