Reputation: 127
I'm trying to define a function that, given an associative array, would echo the key value pair, given an argument for that function.
So far I have the code that appears below. However, the result of that code would be a complete list (table) of the key-value pairs. What I'm trying to get is just ONE pair (once the function is called).
Could anybody help me?
Thanks!
enter code here
<!DOCTYPE html>
<html>
<head>
<body>
<h1>List of States</h1>
<?php
$states = array ("AL"=>"Alabama","AK"=>"Alaska","AZ"=>"Arizona","AR"=>"Arkansas","CA"=>"California","CO"=>"Colorado","CT"=>"Connecticut",
"DE"=>"Delaware","FL"=>"Florida","GA"=>"Georgia","HI"=>"Hawaii","ID"=>"Idaho","IL"=>"Illinois","IN"=>"Indiana","IA"=>"Iowa","KS"=>"Kansas",
"KY"=>"Kentucky");
function printState($Abbr) {
global $states;
echo "<table border=1>";
foreach($states as $Abbr => $value) {
echo "<tr>";
echo "<td>";
echo $Abbr;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
printState("CA");
?>
</body>
</html>
Upvotes: 2
Views: 1339
Reputation: 7294
Hi You can also use this
function printState($Abbr) {
global $states;
if (array_key_exists($Abbr,$states)){
return "<table border=1><tr><td>$Abbr</td><td>$states[$Abbr]</td></tr></table>";
}
}
echo printState("AK");
?>
Upvotes: 0
Reputation: 2326
If you must have a function:
function getState($code) {
global $states;
if (array_key_exists($code, $states)) {
return $states[$code];
}
return false;
}
echo getState('GA');
But as Dave Chen suggested, $states[$abbr];
is how you'd do it.
Upvotes: 4