PHP Arrays

Posts about arrays in PHP

PHP Logo

PHP Array Of UK Counties

4th March 2009 - 1 minute read time

Use the following code to create an array of counties in the UK.

PHP Logo

Remove Duplicate Entries In A PHP Array

6th August 2008 - 1 minute read time

Use the following function to remove all duplicate values in an array.

function remove_duplicated_values($array){
 $newArray = array();
 foreach($array as $key=>$val){
  $newArray[$val] = 1;
 }
 return array_keys($newArray);
}

The way this function works is by looping through the array and assigning each value of the array to be a key of a new array and setting the value as 1. As the values of the array are added to the new array any new values will lengthen the array and any duplicate values will reset to be 1.

The keys of the new array are then returned as an array of values using the array_keys() PHP function.

Here is an example of the function in action.

PHP Logo

Serialize And Unserialize With PHP

30th June 2008 - 2 minutes read time

If you have an object or array that you want to save until a later you can use the serialize() and unserialize() functions. The operation of the functions are straightforward. To serialize() an array just pass the serialise function the array like this.

$array = array(1,2,3,4);
$serializedArray = serialize($array);

Now when we print the serialized array out we get the following.

a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;}

This contains all of the data needed to recreate our array. Be careful not to edit this string because it will not work if you want to unserialize it and get the array back. You can store this string in a file or a database so that you can recreate the exact same array at a later date.

PHP Logo

The PHP array_flip() Function And Detecting Functions

26th June 2008 - 2 minutes read time

The array_flip() function in PHP is used to swap the values of an array with the keys. Take the following array.

$array = array('key1'=>'value1', 'key2'=>'value2');

To exchange all the values with the keys we pass it through the array_flip() function.

$array = array_flip($array);
echo '<pre>'.print_r($array, true).'</pre>';

This prints out the following:

Array
(
 [value1] => key1
 [value2] => key2
)

If any of the values are the same then the highest key is overwritten. The following array:

$array = array('a', 'a', 'a', 'b');

Will produce the following array when passed through array_flip().

PHP Logo

Sorting A Multidimensional Array With PHP

9th June 2008 - 4 minutes read time

Sorting an array is easy in PHP thanks for the built in sorting functions. However, when it comes to sorting a multidimensional array you need to employ these functions in a certain way, especially if you want to vary the data item you want to sort by.

Take the following defined array, taken from the top news stories in the Science and Nature section of the BBC website.

PHP Logo

Remove Blank Entries From An Array With PHP

2nd June 2008 - 2 minutes read time

If you have an array that you want to remove any null data items from then you can use the following function. It will create a new array and only copy across items from the existing array if they contain a value. If the value is an array the function calls itself and makes sure that the returned array contains something before adding it to the new array.

function array_purge_empty($arr) {
 $newarr = array();
 foreach ($arr as $key => $val) {
  if (is_array($val)) {
   $val = array_purge_empty($val);
   // does the result array contain anything?
   if (count($val) != 0) {
    $newarr[$key] = $val;
   }
  } else {
   if (trim($val) != "") {
    $newarr[$key] = $val;
   }
  }
 }
 return $newarr;
}

Here is an example of the function in action.

PHP Logo

Split An Array Into Smaller Parts In PHP

17th May 2008 - 2 minutes read time

Splitting an array into sections might be useful for setting up a calendar or pagination on a site. Either way there are numerous ways to do this but the following seems to be the quickest and most reliable method.

function sectionArray($array, $step)
{
 $sectioned = array();
 
 $k = 0;
 for ( $i=0;$i < count($array); $i++ ) {
  if ( !($i % $step) ) {
   $k++;
  }
  $sectioned[$k][] = $array[$i];
 }
 return $sectioned;
}

Run the function by passing it an array, in this case I am going to split the alphabet into 5 arrays of 5 letters.

$array = range('a','z'); // create an array from a to z
 
echo '<pre>'.print_r(ArraySplitIntoParts_Shorter($array,5),true).'</pre>';

This produces the following output.

PHP Logo

HTML Checkbox To PHP Array

3rd April 2008 - 2 minutes read time

To create a simple HTML check box use the following bit of code.

<input type="checkbox" name="option2" value="Milk" />

To set the checkbox as filled in include a checked attribute. To make the control XHTML compliant you will need to do the following.

<input type="checkbox" name="option2" value="Milk" checked="checked" />

When the form is posted this value is sent to PHP with the $_POST superglobal array.

To link several checkboxes together to make them into an array in the PHP $_POST array you need to make all of the checkboxes have the same name, and each name must end in "[]".

<input type="checkbox" name="option[]" value="1" />
<input type="checkbox" name="option[]" value="2" />

When both of the checkboxes are filled and the form is submitted this produces the following array.

PHP Logo

Array Sorting Algorithms In PHP

1st April 2008 - 7 minutes read time

There are many ways to sort an array in PHP, the easiest being to use the sort() function built into PHP. This sort function is quick but has it's limitations, especially when sorting things like dates as PHP usually guesses which value is higher than the other and can produce odd results. However, there are plenty of sorting algorithms available than can allow you to sort an array in any way you want.

The simplest of these is called the bubble sort. Here is a function that will sort an array of values using the bubble sort algorithm.

PHP Logo

PHP array_merge() Function Improvement

31st March 2008 - 2 minutes read time

The array_merge() function in PHP is a handy way of adding one or more arrays together. Here is an example of how to use it.

$array1 = array(3, 21, 12); // set up first array
$array2 = array(63, 1, 9); // set up second array
$array3 = array_merge($array1, $array2); // merge arrays
print_r($array3); // print!

This will print the following.

Array
(
 [0] => 3
 [1] => 21
 [2] => 12
 [3] => 63
 [4] => 1
 [5] => 9
)

The only problem with this function is that it resets any numeric keys, so the following example would produce the wrong result.