March 23, 2012

Search array key from form post and get sub array

Question by Vince Lowe

I have an array which is storing server addresses like so

$servers = array(
  'UK'=>array(
    'voi' =>  '54.53.23.32',
    'gps' =>  '55.65.34.34',
    'sos' =>  '54.54.34.23'
  ),
  'USA'=>array(
    'voi' =>  '12.23.45.67',
    'gps' =>  '65.443.23.45',
    'sos' =>  '12.23.456.4'
  )
);

I have a form which is listing the server locations

<select name="server" id="server">
<?php foreach($servers as $key => $arr){
echo "<option>" .$key. "</option>"; }
?>
</select>

Once the form is submitted i need to set a session variable with the correct countrys IP’s

$_SESSION['voi']=$submitted_countrys_voi_ip;
$_SESSION['gps']=$submitted_countrys_gps_ip;

etc..

How can i choose the correct key based on the form post and get the values from the sub array into a session variable?

Answer by Starx

First of all, you select does not have a value. So fixed that first

<select name="server" id="server">

    <?php foreach($servers as $key => $arr){
    echo "<option value='$key'>" .$key. "</option>"; }
    ?>

</select>

Then, after the form is submitted. Assuming that form is submitted using POST method

$server = ..; //Being your array of ips
$sub_server = $_POST['server']; //get the submitted server
$_SESSION['voi'] = $server[$sub_server]['voi'];
$_SESSION['gps'] = $server[$sub_server]['gps'];
// and so on

Improvement

In case you have lots of IP’s for a nation, then you might want to create an array of the types first.

$server = ..; 
$types = array('voi','gps', 'sos'); //TYPES in a single array
$sub_server = $_POST['server']; 
foreach($types as $type) {
    $_SESSION[$type] = $server[$sub_server][$type];
}

This is automatically assign every types at once.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!