4 PHP Tricks for Associative Array Manipulation

The associative array is indispensable to almost every programmer for being a data type that can be used to describe a collection of unique keys and associated values.

In fact, this aspect of programming is so integral to web development that PHP supports a number of functions and features that carries out this tasks of manipulating arrays in a number of ways.

That said, here are 4 ways you can manipulate data to suit any purpose of yours:

#1: Removing Array Elements

If you want to remove an array element, you have to use the unset() function. For example, you can use the following syntax: unset($capitals[‘California’]);

Alternatively, you can use the functions array_shift() and array_pop() to remove an element from the beginning and end of an array.

 #2: Merging Arrays

 Let’s say that you want to test the knowledge of students, in terms of Cialis Online states or countries and their capitals, and have created seperate arrays in the past for both these types of data. So, if you want to merge these arrays easily by using the array_merge() function.

 The syntax for the arrays, $stateCapitals and $countryCapitals is: $capitals = array_merge($stateCapitals, $countryCapitals);

 #3: Swapping Keys and Values

 Now using the example above, let’s say you wanted to create a new array named $states where you would use the state capitals as the index and the state names as the associated value, this can be done using the array_flip() function.

 The syntax for this would be: $states = array_flip($capitals);

 #4: Editing Array Values

Now let’s say you find capitalization errors in the state capitals, and want to correct them before inserting them back into the database. You’ll use the array_map() function for this purpose.

 The syntax would be: $capitals = array_map(“capitalize”, $capitals);