Hi everyone,

I am trying to write a function that will check the ID of a list of states and return the Abbreviation. I can get it to work with a complete list of states, but when I try to pass just one state to it, it returns nothing.

Here is the function:

function SA($var) {
$i=1;
	foreach($var as $key => $sa) {
		if(array_key_exists($i, $var)) {
			echo 'state[' . $i . '] = ' . $sa . '<br>';
			$i++;
		}
	}

}

And when I pass this array to it, it returns the results I expect.

$StatesAbbr
Array
(
    [1] => AK
    [2] => AL
    [3] => AZ
//etc....

But to test it, I tried passing this array to it and I get no results.

$StatesAb  = array(39=>"PA");

My states table is like this:
statesid Name Abbreviation
1------------Alaska------AB
2------------Alabama----AL
etc.

My end result is I am going to get a set of rows from my customer table, and I want to change the State[id] stored in that table to the matching state abbreviation in my second table. And I am using this result set to write out a CSV (which I have working except for whitching the ID to the abbreviation).

I hope that makes sense.

As always, I appreciate the help.
regards,
Don

    While I'm not entirely sure what you want to happen, I'm sure that hard-coding the starting index ("$i") value at 1 within the function means you'll only get results if the array's starting index is 1 and all other indexes are sequentially numbered.

    Perhaps all you need is:

    function SA($var)
    {
       foreach($var as $key => $sa)
       {
          echo 'state['.$key.'] = '.$sa."<br>\n";
       }
    }
    

      Thanks, NogDog, that was my problem and your solution worked great.

      I was under the misconception, I would need to increment it manually, and did not realize that it would have the effect you explained.

      Thanks again,

      Don

        Write a Reply...