|
Solution 9
Main | Arrays | Practice 8 | Solution 8 | Associative Arrays | Practice 9 | Solution 9 | Regular Expressions | Practice 10 | Solution 10 | More Regular Expressions | Practice 11 | Solution 11 Here is the solution to Practice 9:
<?php
function key_of_val($search, $some_ar) {
$result = "Sorry couldn't find \"$search\". ";
foreach ($some_ar as $key => $val) {
if ($val == $search) {
$result = "The key of \"$search\" is \"$key\". ";
}
}
return $result;
}
function flip_it($some_ar) {
$result = array();
foreach ($some_ar as $key => $val) {
$result["$val"] = $key;
}
return $result;
}
$some_ar = array(
"greeting" => "hello",
"farewell_message" => "goodbye"
);
print key_of_val("hello", $some_ar);
print "<br>";
print key_of_val("greeting", $some_ar);
print "<br>";
$some_ar = flip_it($some_ar);
print "<p>Inverted the array";
print "<p>";
print key_of_val("hello", $some_ar);
print "<br>";
print key_of_val("greeting", $some_ar);
print "<br>";
?>
Note that as of PHP4 there is a function called array_flip which does what flip_it() does.
jfulton [at] member.fsf.org
|