0

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("&nbsp;&nbsp;&nbsp;&nbsp;$country");
?>
8
  • Your countryName function doesn't have access to the $countryCode variable. Also, assigning values to $country within 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? Commented Dec 23, 2018 at 17:30
  • I guess I don't understand scope in php... I would expect $countryCode to be a global variable as it's defined in the file scope outside of any function. I guess scope is different in php and I need to do more research. What I've got coming in is 'AF' but what I'm wanting is 'Afghanistan' Commented Dec 23, 2018 at 17:35
  • 1
    Yeah it would be the case in most languages. In PHP, you would have to either access it via $GLOBALS['countryCode'] or declare it as global at the beginning of your function, with global $countryCode;. Commented Dec 23, 2018 at 17:41
  • Thanks, it works that way, but I always get 'not found' Commented Dec 23, 2018 at 18:12
  • I had key/value reversed in the function. Now it's working in a playground with a hard coded value but not live - presumably because of htmlspecialchars but I'm not sure how to handle that Commented Dec 23, 2018 at 18:25

3 Answers 3

1

According to comments, you're simply looking for an array value given a key:

$countryCode = 'AF';
$countryArr = array('AF' => 'Afghanistan');

$countryName = $countryArr[$countryCode] ?? null;

The ?? null part (requires PHP7) ensures $countryName will be null even if the country code doesn't exist as a key in the array.

Note that this is extremely basic PHP, I would recommend reading up on the subject of arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

As I said, I'm just winging it right now. I managed to write a script that processes a form into a SQL db without learning about arrays. Life doesn't have to be from point A to Z in sequential order. I'll get there my way. Thanks very much for the help
1

If you need to return key from value, You don't need to create a function for that or use array_walk. Instead this array_search will also work.

$key = array_search ('country_name', $countryArr);

3 Comments

Why are you passing a key to it? You want the value from the key or the key from the value? If it's the former, it's just a simple array access: $countryArr[$countryCode]...
@Jeto That works on playground and live. I'd like to give you credit if you want to put an answer up
@froggomad Just did.
0
<?php
$languages =
[
    'fr' => 'French',
    'es' => 'Spanish'
];

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (
        isset($_POST['lang'])
        && is_string($_POST['lang'])
        && array_key_exists($_POST['lang'], $languages)
    )
    {
        $language = $languages[$lang];
    }
    else 
    {
        throw new Exception('Invalid language code.');
    }

    echo $language;
}

?>
<form method='post'>
    <select name='lang'>
        <?php foreach($languages as $k => $v) { ?>
            <option value='<?=$k?>'><?=$v?></option>
        <?php } ?>
    </select>
    <input type='submit'>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.