Category: PHP Arrays

Remove Duplicate Entries In A PHP Array

6 August, 2008 | PHP Arrays | 2 comments

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.

$array = array(1,1,1,1,1,2,3,4,5,6,6,6,6,6,6,6,6,6,6);
echo '<pre>'.print_r($array,true).'</pre>';
$array = remove_duplicated_values($array);
echo '<pre>'.print_r($array,true).'</pre>';

Be aware that any keys that the original array has will be lost by the action of this function.

Serialize And Unserialize With PHP

30 June, 2008 | PHP Arrays | No comments

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.

If you do chose to store the serialized string in a database you might want to encode it as well. This is to stop the database encoding or removing any characters and destroying your array. To encode the string you can use the base64_encode function in this way.

$encodedSerializedArray = base64_encode(serialize($array));

This string now contains the following.

YTo0OntpOjA7aToxO2k6MTtpOjI7aToyO2k6MztpOjM7aTo0O30=

To get the array back again we use the unserialize() function like this. If you used the base64_encode() to encode the array then you can use the base64_decode() function to turn it back into an unserializable string again.

$array = unserialize($array);

The $array variable now contains our original array.

The same can also be done with objects in exactly the same way. The main difference is that PHP will try to call the __wakeup() function of the object (if it exists) once it has been reconstructed.

The PHP array_flip() Function And Detecting Functions

26 June, 2008 | PHP Arrays | No comments

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().

Array
(
 [a] => 2
 [b] => 3
)

If this bit of code is essential to the running of your program you can make sure that it exists by using the function_exists() function. This function takes a single parameter, which is the name of the function you are testing for as a string. The following code checks to see if the array_flip() function exists, and if not defines a version that works in the same way.

if(!function_exists('array_flip')){
 function array_flip($array){
  $values = array();
  while(list($key,$val) = each($array))
  $Values[$val] = $key;
  return $values;
 }
}

The array_flip() function was included in PHP version 4, so you only need to do this if you expect someone to try and run your code on an old version of PHP. However, there are many new fucntions included with PHP 5 that you might want to check for when writing code.

Sorting A Multidimensional Array With PHP

9 June, 2008 | PHP Arrays | No comments

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.
$bbcNews = array(
 array('Martian soil frustrates Phoenix','7442233','Science/Nature','Saturday, 7 June 2008 00:25'),
 array('Natural lab shows sea\'s acid path','7437862','Science/Nature','Sunday, 8 June 2008 18:08'),
 array('Hints of "time before Big Bang"','7440217','Science/Nature',' Friday, 6 June 2008 15:43'),
 array('Bacteria could stop frog killer','7438205','Science/Nature','Friday, 6 June 2008 08:46')
);

In order to sort the array by any item I will use the PHP function usort(). This function takes two parameters, the first is the array that is to be sorted and the second is a string which will be used as a callback function to allow comparison between one item and the next. All of the sorting intricacies are sorted out behind the scenes, all you have to do is get this comparison function to return a 0 when the two values are the same, a negative number if the first is less and the second and a positive value when the first is greater than the second. The following bit of code will run the sort function on the array, it doesn’t have a return value as the array itself is sorted.

usort($bbcNews, 'sortcompare');

Before we define the sortcompare() function we will use a variable to store the item of the array that we wish to sort by. This variable is called $sort_field.

$sort_field = 1; // enter the number of field to sort

In order to use this variable we will include it in the scope of the function using the global command. At the moment this will cause the function to sort by the ID number of the news article (the second item in the array). Just change this to whatever array item that you want to sort by. Remember that, as will all PHP arrays (unless you set otherwise), this number starts from zero.

Here is the callback function that is used to sort the array. It is split into three parts. First it tries to convert the string into a date, if this is successful it returns a comparison value based on the previously mentioned negative, zero and positive values. If both the values can’t be converted into dates it check to see if they are numeric. If neither of these two situations are true then the PHP function strcasecmp() is run on the two strings. This is a binary safe case-insensitive string comparison function.

// compare function
function sortcompare($a, $b){
 // include $sort_field variable
 global $sort_field;
 if(($timea = strtotime($a[$sort_field]))!==false && ($timeb = strtotime($b[$sort_field]))!==false){
  // time comparison
  if($timea ==$timeb){
   return 0;
  }
  return ($timea < $timeb) ? -1 : 1;
 }elseif(is_numeric($a[$sort_field]) && is_numeric($b[$sort_field])){
  // numeric sort
  if($a[$sort_field] ==$b[$sort_field]){
   return 0;
  }
  return ($a[$sort_field] < $b[$sort_field]) ? -1 : 1;
 }else{
  // normal case insensitive string comparison
  return strcasecmp($a[$sort_field], $b[$sort_field]);
 }
}

To print out the output of this function use the following bit of code. This will verify that the function works by printing out the array in full.

echo '<pre>'.print_r($bbcNews,true).'</pre>';

Remove Blank Entries From An Array With PHP

2 June, 2008 | PHP Arrays | No comments

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_remove_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.

// create array with some null items in it.
$array = array('a','b'=>'',3,0,' ',NULL,'',array(),array(1),4);
// print array
echo '<pre>'.print_r($array,true).'</pre>';
// print result of array_purge_empty() function
echo '<pre>'.print_r(array_purge_empty($array),true).'</pre>';

This produces the following output.
Array
(
 [0] => a
 [b] =>
 [1] => 3
 [2] => 0
 [3] =>
 [4] =>
 [5] =>
 [6] => Array
  (
  )
 
 [7] => Array
  (
   [0] => 1
  )
 
 [8] => 4
)
 
Array
(
 [0] => a
 [1] => 3
 [2] => 0
 [7] => Array
  (
   [0] => 1
  )
 
 [8] => 4
)