Specifications

For example, the following code
$array = array(4, 5, 1, 2, 3, 1, 2, 1);
$ac = array_count_values($array);
creates an array called $ac that contains
Key Value
41
51
13
22
31
This indicates that 4, 5, and 3 occurred once in $array, 1 occurred three times, and 2 occurred
twice.
Converting Arrays to Scalar Variables: extract()
If we have an associative array with a number of key value pairs, we can turn them into a set
of scalar variables using the function extract(). The prototype for extract() is as follows:
extract(array var_array [, int extract_type] [, string prefix] );
The purpose of extract() is to take an array and create scalar variables with the names of the
keys in the array. The values of these variables are set to the values in the array.
Here is a simple example.
$array = array( “key1” => “value1”, “key2” => “value2”, “key3” => “value3”);
extract($array);
echo “$key1 $key2 $key3”;
This code produces the following output:
value1 value2 value3
The array had three elements with keys: key1, key2, and key3. Using extract(), we created
three scalar variables, $key1, $key2, and $key3. You can see from the output that the values of
$key1, $key2, and $key3 are “value1”, “value2”, and “value3”, respectively. These values
came from the original array.
There are two optional parameters to extract(): extract_type and prefix. The variable
extract_type tells extract() how to handle collisions. These are cases in which a variable
already exists with the same name as a key. The default response is to overwrite the existing
variable. Four allowable values for extract_type are shown in Table 3.1.
Using Arrays
C
HAPTER 3
3
USING ARRAYS
91
05 7842 CH03 3/6/01 3:42 PM Page 91