简体   繁体   中英

PHP Associative array. Get key value pair using foreach

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>

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.

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");
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM