The associative array -- an indispensable data type used to describe a collection of unique keys and associated values -- is a mainstay of all programming languages, PHP included. In fact, associative arrays are so central to the task of Web development that PHP supports dozens of functions and other features capable of manipulating array data in every conceivable manner. Such extensive support can be a bit overwhelming to developers seeking the most effective way to manipulate arrays within their applications. In this article, I'll offer 10 tips that can help you shred, slice and dice your data in countless ways.
1. Adding Array Elements
PHP is a weakly typed language, meaning you're not required to explicitly declare an array nor its size. Instead you can both declare and populate the array simultaneously:
$capitals = array(
  'Alabama' => 'Montgomery',
  'Alaska'  => 'Juneau',
  'Arizona' => 'Phoenix'
);
Additional array elements can be appended like this:
$capitals['Arkansas'] = 'Little Rock';
If you're dealing with numerically indexed arrays and would rather prepend and append elements using an explicitly-named function, check out the array_push() and array_unshift() functions (these functions don't work with associative arrays).
2. Removing Array Elements
To remove an element from an array, use the unset() function:
unset($capitals['California']);
When using numerically indexed arrays you have a bit more flexibility in terms of removing array elements in that you can use the array_shift() and array_pop() functions to remove an element from the beginning and end of the array, respectively.
3. Swapping Keys and Values
Suppose you wanted to create a new array called $states, which would use state capitals as the index and state names as the associated value. This task is easily accomplished using the array_flip() function:
$capitals = array(
  'Alabama' => 'Montgomery',
  'Alaska'  => 'Juneau',
  'Arizona' => 'Phoenix'
);
$states = array_flip($capitals);
// $states = array(
//  'Montgomery' => string 'Alabama',
//  'Juneau'     => string 'Alaska',
//  'Phoenix'    => string 'Arizona'
// );
4. Merging Arrays
Suppose the previous arrays were used in conjunction with a Web-based "flash card" service, and you wanted to provide students with a way to test their knowledge of worldwide capitals, U.S. states included. You can merge arrays containing both state and country capitals using the array_merge() function:
$stateCapitals = array(
  'Alabama' => 'Montgomery',
  'Alaska'  => 'Juneau',
  'Arizona' => 'Phoenix'
);
$countryCapitals = array (
  'Australia' => 'Canberra',
  'Austria'   => 'Vienna',
  'Algeria'   => 'Algiers'
);
$capitals = array_merge($stateCapitals, $countryCapitals);
5. Editing Array Values
Suppose the data found in an array potentially contains capitalization errors, and you want to correct these errors before inserting the data into the database. You can use the array_map() function to apply a callback to every array element:
function capitalize($element)
{
  $element = strtolower($element);
  return ucwords($element);
}
$capitals = array(
  'Alabama' => 'montGoMEry',
  'Alaska'  => 'Juneau',
  'Arizona' => 'phoeniX'
);
$capitals = array_map("capitalize", $capitals);
6. Sorting Arrays by Keys
Flashcard applications often employ a variety of learning techniques involving sorting cards in certain ways, such as alphabetically. You can sort associative arrays by key using the ksort() function:
$capitals = array(
  'Arizona' => 'Phoenix',
  'Alaska'  => 'Juneau',
  'Alabama' => 'Montgomery'
);
ksort($capitals);
Because the array is passed by reference, ksort() will sort the array "in place," meaning you won't have to assign the sort results to another variable.
7. Randomizing Array Order
Still another flashcard technique involves randomly sorting the cards. You can easily randomize an array's entry order using the shuffle() function:
$capitals = array(
  'Arizona' => 'Phoenix',
  'Alaska'  => 'Juneau',
  'Alabama' => 'Montgomery'
);
shuffle($capitals);
If rather than shuffling the array you instead wanted to randomly select a value, check out the array_rand() function.
8. Determining Whether Keys and Values Exist
You can use the in_array() function to determine whether an array element exists:
$capitals = array(
  'Arizona' => 'Phoenix',
  'Alaska'  => 'Juneau',
  'Alabama' => 'Montgomery'
);
if (in_array("Juneau", $capitals))
{
  echo "Exists!";
} else {
  echo "Does not exist!";
}
Lesser known is the ability to also determine whether an array key exists, a feat accomplished with the array_key_exists() function:
$capitals = array(
  'Arizona' => 'Phoenix',
  'Alaska'  => 'Juneau',
  'Alabama' => 'Montgomery'
);
if (array_key_exists("Alaska", $capitals))
{
  echo "Key exists!";
} else {
  echo "Key does not exist!";
}
9. Searching the Array
You might consider making the flashcard learning resource searchable, so users can easily retrieve a state associated with a particular capital. This can be done using the array_search() function:
$capitals = array(
  'Arizona' => 'Phoenix',
  'Alaska'  => 'Juneau',
  'Alabama' => 'Montgomery'
);
$state = array_search('Juneau', $capitals);
// $state = 'Alaska'
10. The Standard PHP Library
The Standard PHP Library (SPL) offers developers with quite a few data structures, iterators, interfaces, exceptions and other features not previously available within the PHP language. Among these features is the ability to iterate over an array using a convenient object-oriented syntax:
$capitals = array(
  'Arizona' => 'Phoenix',
  'Alaska'  => 'Juneau',
  'Alabama' => 'Montgomery'
);
$arrayObject = new ArrayObject($capitals);
foreach ($arrayObject as $state => $capital)
{
  printf("The capital of %s is %s<br />", $state, $capital);
}
// The capital of Arizona is Phoenix
// The capital of Alaska is Juneau
// The capital of Alabama is Montgomery
This is just one of countless great features bundled into the SPL, be sure to consult the PHP documentation for more information.
About the Author
Jason Gilmore is the founder of the publishing and consulting firm WJGilmore.com. He also is the author of several popular books, including "Easy PHP Websites with the Zend Framework", "Easy PayPal with PHP", and "Beginning PHP and MySQL, Fourth Edition". Follow him on Twitter at @wjgilmore.