Practice 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

In this practice we will do the following:

  1. Write a function key_of_val() which takes a value and an associative array as its arguments and then tells you the key that the value maps to in the array or that the value was not found.

    For example given the following array:

    $a = array(
    	 "greeting" => "hello",
    	  "farewell_message" => "goodbye"
    	 );
    

    key_of_val("hello", $a) will return "greeting"

    and

    key_of_val("howdy", $a) will return a message saying "howdy wasn't found".

  2. Write a function flip_it() which takes an associative array as an argument and inverts it such that the values become the keys and the keys become the values.

    For example given the following array:

    $a = array(
    	 "greeting" => "hello",
    	  "farewell_message" => "goodbye"
    	 );
    
    $a = flip_if($a) will transform $a such that it would become:
    $a = array(
    	   "hello" => "greeting",
    	   "goodbye" => "farewell_message"
    	 );
    

In the sample code that you will be practicing on top of the function flip_it() is setup to return the array it takes as an argument by default. This simplified version of the function contains what is called a "stub". It is some code that makes a function return a value so that it doesn't get in the way while you are trying to write other functions. After you finish part one from the above start part two by removing the stub and making the function actually return an inverted array. The stub is commented out.

To complete this exercise you must:

  • Create a file in "public_html/php" called "invert.php".
  • Be sure that "invert.php" is viewable from the web.
  • Fill in "invert.php" with this incomplete code.

Note that in the bottom of the incomplete code there is code to test the functions. You don't need to edit that code. You only need to implement the functions.


jfulton [at] member.fsf.org
22 Aug 2013