<<

. 30
( 132 .)



>>


COMPACT() compact() and extract() are used to convert array elements into
variables and vice versa, respectively.

array compact (mixed varname [, mixed ...])

Given a list of variable names (passed either as individual arguments or as an
array), compact() outputs an array whose keys are the variable names and whose
values are the respective values of those variables. Only variables whose values are
set will be included in the output array.

EXTRACT()

int extract (array assoc_array [, int extract_type_constant [, string prefix]])


To pull key/value pairs from an array and make them into standalone variables,
use extract(). The element key will become the name of the variable, and the ele-
ment value will become the value of the variable. Therefore, this code
154 Part II: Working with PHP

$array = array(“name” => “Jay”,
“brand” => “Cohiba”);
extract($array, “name”);
echo $name;

will output this:

Jay

The extract_type_constant argument controls how namespace collisions are
handled. The constant takes any of eight predefined values (see the PHP manual
page on this at http://php.net/extract) such as EXTR_OVERWRITE and
EXTR_SKIP. These dictate what the parser should do when it encounters collisions.

NUMBER_FORMAT()

string number_format (float number [, int decimals [, string dec_point , string
thousands_sep]])


Given a floating-point number, this function returns a string formatted for
human consumption, containing the number with thousands separators and a dec-
imal separator. By default these are a comma and a dot, respectively, but other sym-
bols can be specified.

JOIN()

string join (string glue, array pieces)

Given an array and a string, join() returns a string comprised of the elements
of the array concatenated in order, with the glue string between each two elements.


join() is identical to the implode() function.




RANGE()

array range (mixed from, mixed to [, int increment])

This function creates an array and automatically populates it with elements
ranging from from to to. If a step increment is specified in the third argument, that
will be the increment between elements; otherwise the increment will be one.
Chapter 6: PHP™s Built-in Functions 155

TYPE CONVERSION FUNCTIONS NOT USED IN THIS BOOK
In addition to the functions in the previous section, you can make use of spliti(),
which uses a case-insensitive pattern match. Other than the case-insensitivity with
respect to alphabetic characters, spliti() works just like split(). Consider these:

$audienceResponse1 = “oooooAAAooooh”;
$audienceResponse2 = “oooooaaaooooh”;
list ($part1, $part2) = split(˜[AAA]™, $audienceResponse1);
list ($part3, $part4) = spliti(˜[aaa]™, $audienceResponse2);

As a result of that, $part1 and $part3 contain ooooo, while $part2 and $part4
contain ooooh.

Array functions
We are big fans of the array functions available in PHP. Just about anything you™d
like to do to an array you can do with a built-in function. The developers of PHP
have done a good job of making sure you don™t have to loop though arrays very
frequently, if ever.
The PHP manual lists exactly 60 array functions as of this writing. It™s likely that
by the time you read this chapter, there will be several more. So make sure you scan
the manual to see the full range of available array functions.


See Chapter 5 for a discussion of how to create, add to, and walk through an
array.




ARRAY FUNCTIONS USED IN THIS BOOK
Here™s a rundown of the array functions we use in this book.

ARRAY_FLIP() This function, which is useful with associative arrays, exchanges
keys and values. That is, the keys become the values and the values become the keys.

array array_flip (array trans)

We use this function once in the course of the book, in the following code:

$trans = array_flip(get_html_translation_table(HTML_ENTITIES));
$title = strtr($title, $trans);
156 Part II: Working with PHP

Before the array_flip() function, the array holds many elements. Here are a
couple of examples:

[(c)] => &copy
[(r)] => &reg

Once the array is flipped, these entries will look like this:

[$copy] => (c)
[&reg] => (r)

Then strtr() replaces each value with its key. So in the end this code will make
sure that any character that needs to be represented by an HTML entity will be.
Note that if an array has two keys with identical values before being flipped,
only one can survive in the flipped array. You can™t have two array elements with
same key. If conflict arises, the element in the position with the highest index value
will be maintained.

ARRAY_MERGE() As you can probably guess, this function merges, or concate-
nates, two or more arrays.

array array_merge (array array1, array array2 [, array ...])

If two or more of the arrays contain the same associative keys, the elements with
the highest index values will be preserved.

ARRAY_SPLICE() This function takes the array indicated in the first argument and
removes all elements following the offset specified in the second argument. It can
then insert additional elements.

array array_splice (array input, int offset [, int length [, array
replacement]])


If the offset is a positive number, the elements will be counted from the left; if
the offset is a negative number, all items to the left of the indicated number will be
deleted. The optional third argument can indicate how many elements after the off-
set you wish to delete. For example, this code

$knicks_array = array (“Childs”, “Sprewell”, “Ewing”,
“Johnson”,”Houston”);
array_splice($knicks_array, 2,1);

will remove elements starting at offset 2 and remove only one element. So Ewing
will be deleted from this array. array_splice() also gives you the ability to replace
the deleted portion with another array. So, to account for trades, you can do this:
Chapter 6: PHP™s Built-in Functions 157

$knicks_array = array(“Childs”, “Sprewell”, “Ewing”,
“Johnson”,”Houston”);
$new_knicks = array(“Longley”,”Rice”);

array_splice($knicks_array, 2,1,$new_knicks);

Following this code, $knicks_array will contain six elements: Childs,
Sprewell, Longley, Rice, Johnson, Houston.
Note that the value returned by this function is an array of the deleted items. In
the code that follows, $traded_knicks will be an array with one element, Ewing:

$knicks_array = array(“Childs”, “Sprewell”, “Ewing”,
“Johnson”,”Houston”);
$traded_knicks = array_splice($knicks_array, 2,1);

COUNT() This function returns the number of elements in an array, and is fre-
quently used with loops.

int count (mixed var)

For example:

$array = array(1,2,3,4,5);
$len = count($array);
for ($i=0; $i < $len; $i++)
{
echo $array[$i] . “<br>\n”;
}

Note that sizeof() is a synonym for count().

ARRAY_FILTER()

array array_filter (array input, callback function)

This function returns a new array consisting of only those elements of the input
array that pass through a filtering function.
Here is a simple code snippet illustrating how the function can be used:

function test_score($var) {
global $score;
return ($var > $score);
}
$winners = array_filter($players, “test_score”);
158 Part II: Working with PHP

To illustrate the behavior of that function, imagine that $players initially con-
tained this list:

45, 35, 21, 8, 17, 12, 10

Further imagine that the global variable $score held 10. At the end of the code
snippet just illustrated, $winners would contain this:

45, 35, 21, 17, 12

ARRAY_KEY_EXISTS()

bool array_key_exists (mixed key, array search)

This function takes a key name and an array as arguments, and returns a
Boolean value indicating whether the key exists in the array.

ARRAY_KEYS()

array array_keys (array input [, mixed value])

With only one argument, this function returns all the keys of an array. If it is
given a value as a second argument, it returns all keys with that value.

ARRAY_MAP()

array array_map (mixed function, array array1 [, array array2...])

This function takes an array and a function as arguments, and passes each ele-
ment of the array to the function. It returns an array consisting of the return values
generated by the called function for each element, in the original order. So, given

function halve($var) {
return $var / 2 ;
}
$half = array_map(“halve”, array(16, 8772, 566, 100));

now $half contains:

Array
(
[0] => 8
[1] => 4386
[2] => 283
[3] => 50
)
Chapter 6: PHP™s Built-in Functions 159

Note that the called function must not modify the array itself.

ARRAY_DIFF() If given two arrays, this function will return all the elements that
are in the first array but not in the second array.

array array_diff (array array1, array array2 [, array ...])

For example:

$knicks = array(“sprewell”, “houston”, “ewing”, “childs”);
$all_stars = array(“mourning”, “houston”, “carter”, “davis”,
“miller”);
$non_knick_allstars = array_diff($all_stars, $knicks);

Note that in the returned array, the elements maintain the keys they had in the
array from which they were taken. So, after this code is run, $non_knick_allstars
will contain the following:

<<

. 30
( 132 .)



>>