PHP5: Arrays

Posted on January 31, 2011

PHP5 adds some new functions for working with arrays. Here’s an overview.

array_combine() takes 2 arrays — one with keys and one with the values — and combines them into a single key-based array (hash):

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

The $c array will then be:

Array
(
  [green]  => avocado
  [red]    => apple
  [yellow] => banana
)

array_fill_keys() is similar to array_combine(), but rather than take an array of values, it takes a single value and uses that as the value for each key:

$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');

The $a array is now:

Array
(
  [foo] => banana
  [5] => banana
  [10] => banana
  [bar] => banana
)

array_replace() replaces elements in a given array with elements from one or more arrays, matching them by key. An example should illustrate:

$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$basket = array_replace($base, $replacements, $replacements2);

This would result in the array:

Array
(
  [0] => grape
  [1] => banana
  [2] => apple
  [3] => raspberry
  [4] => cherry
)

There is also an array_replace_recursive() function, which will recurse into elements that are arrays and perform the same replacement process on them.

array_walk_recursive() works like the old array_walk(), but if an element is an array, it will recurse into that array and “walk” along those elements too.

PHP5 also extends the existing functions of array_diff() and array_diff_assoc() with new functions that accept a user-defined callback function for comparison (indicated by a “u” prefix), rather than using the built-in comparison:

  • array_udiff()
  • array_udiff_assoc()
  • array_udiff_uassoc()
  • array_diff_uassoc()

They did the same with the array_intersect() function, allowing you to define your own comparison functions for determining the overlap of values and keys:

  • array_uintersect()
  • array_uintersect_assoc()
  • array_uintersect_uassoc()

Check out the PHP manual for details on all these functions. They’re nothing amazing, but can make life easier so you don’t have to write them yourself.

Leave a Reply

One Response to PHP5: Arrays

  1.  

    |