First let me start off saying I'm brand new to php and winging it. I'm open to alternate methods for achieving the result and any criticism.
I've got a form with a list of country codes. The list is formatted so the country code is the value and the country is the text.
<option value="AF">Afghanistan</option>
I'm wanting the country rather than the country code to be input into the database without having to change the html.
In the php file processing the form, I'm using htmlspecialchars to prevent XSS
$countryCode = htmlspecialchars($_POST["user_country"], ENT_QUOTES, 'UTF-8');
I put the country codes into an array as keys, and the name as values.
$countryArr = array('AF' => 'Afghanistan');
I created a variable to hold the name of the country
$country = '';
I created a function to find the value and write the key to $country
function countryName($value, $key) {
if ($countryCode == $value) {
$country = $key;
} else {
$country = 'not found';
}
}
I walk the array using the above function
array_walk($countryArr, 'countryName');
The output I'm expecting is the country name or 'not found' but what I'm getting is an empty string.
What I've got now works in a playground, but not live, presumably because of htmlspecialchars - but I don't know how to handle that. I'm using htmlspecialchars as a way to escape the string, bypassing common XSS attacks
Works in playground
<?php
$countryCode = 'AF';
$countryArr = array('AF' => 'Afghanistan');
$country = '';
function countryName($value, $key) {
global $countryCode, $country;
if ($countryCode == $key) {
$country = $value;
} else {
$country = 'not found';
}
}
array_walk($countryArr, 'countryName');
echo('Country:<br>');
echo(" $country");
?>
countryNamefunction doesn't have access to the$countryCodevariable. Also, assigning values to$countrywithin that same function doesn't serve any purpose. Can you rephrase what you're trying to do, as simply as possible? Do you want to pass a country name and retrieve the corresponding key?$GLOBALS['countryCode']or declare it as global at the beginning of your function, withglobal $countryCode;.htmlspecialcharsbut I'm not sure how to handle that