Tag Archives: array

PHP: How to Scramble an Array CodeUnit 16 NOV 2011

PHP comes packaged with an awesome little function that makes scrambling an array, i.e. randomly rearranging its contents, a doddle. Aptly named shuffle, the shuffle() function randomizes the order of elements in an array.

As an input array, you simply need to pass it the array to be shuffled, with the function returning either true or false depending on the outcome. The array is passed in by reference, meaning that the original array is shuffled. Note also that existing keys are removed and new keys are assigned, making it useless for associative arrays where the key/value pairs are actually important.

Nevertheless, still a pretty useful function in my opinion. To use:

$numbers = array(1,2,3,4,5);
shuffle($numbers);
print_r($numbers);

Nifty.

PHP: How to Create a Single String of Array Keys using Implode CodeUnit 09 NOV 2011

PHP’s implode function is extremely useful for flattening a one dimensional array into a string. This time around, we want to create a flat string of an array’s keys, ignoring the actual values for a change.

To achieve this is actually very simple – it’s just a matter of combining the stock standard array_keys() and implode() functions together!

So given an array that looks like this:

$myarray = array('green'=>'leaf','blue'=>'sky','red'=>'apple');

We can get a flattened string reading green||blue||red by doing the following:

echo implode('||',array_keys($myarray));

Simple. The array_keys function first returns an array containing the keys of our aforementioned array, before the implode function flattens it using || as a delimiter.

Nifty.

PHP: How to Insert a Value at the Front of an Array CodeUnit 12 SEP 2011

To add or insert a value into the front of a standard array using PHP is actually pretty simple thanks to the nifty little array_unshift function. (If you think about it, it does exactly the opposite of PHP’s array_shift function!)

In practice:

//declare an array to test on
$arr = array('apple','pear');
print_r($arr);

//right, now add 'peaches' to the front of the array
array_unshift($arr,'peaches');
print_r($arr);

//you can even push multiple items onto the front of the array
array_unshift($arr,'apricots','strawberries');
print_r($arr);

The array’s internal numeric index gets automatically renumbered in case you are wondering, meaning that $arr[0] will now point to the last item prepended to the array.

Nifty.

PHP: Return all String Permutations for a 1 Dimensional Array CodeUnit 07 FEB 2011

Getting all the possible string permutations of an array can be pretty useful if you are trying to unlock something and this nifty little function does exactly that:

function array_permutations($items, $perms = array()) {
    static $permuted_array;
    if (empty($items)) {
        $permuted_array[] = $perms;
    } else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
            $newitems = $items;
            $newperms = $perms;
            list($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, $foo);
            array_permutations($newitems, $newperms);
        }
        return $permuted_array;
    }
}

//To use:
$result=array_permutations(array("South","Africa","Rugby","Competition"));
print_r($result); 

Nifty.

PHP: Merge Two Arrays but Keep Their Keys Intact CodeUnit 03 SEP 2010

Combining two or more arrays whilst keeping their keys intact in PHP is deceptively simple – though not if you assume you need to use a function like array_merge to achieve this!

As you scroll through the various array functions available to you, you will notice that quite a few seem to drop the array keys after they are done, which is pretty useless if all you want to do is basically add two arrays to one another to form one big keyed array.

So how do you do this then?

Simple really. Just literally add them together!

$resultarr = $array1 + $array2;

And just in case you are wondering what the hell is going on, remember that when applied to arrays, the + acts as a union operator.

Nice!

PHP: Implode a Multi-dimensional Array CodeUnit 09 APR 2010

PHP’s implode is a pretty handy function to flatten any array into a single string value, using any piece of ‘glue’ (basically a substring) that you specifiy to put everything together.

So in other words, if we had an array containing the string values of cat, dog and chicken and then ran the implode function against them using the character ‘|’ as glue, we would end up with a single string value reading cat | dog | chicken.

Of course, extending this function to handle multi-dimensional arrays (or matrices if you prefer) is a pretty simple matter of quickly whipping up a recursive version and so without any further waffling from my side, here’s the code:

//flattens a multi-dimensional array (recursive implode)
//-----------------------------------------------------------
function r_implode( $glue, $pieces )
{
	foreach( $pieces as $r_pieces )
	{
    		if( is_array( $r_pieces ) )
    		{
      			$retVal[] = r_implode( $glue, $r_pieces );
    		}
    		else	
    		{
      			$retVal[] = $r_pieces;
    		}
  	}
  	return implode( $glue, $retVal );
} 
//-----------------------------------------------------------

Usage is pretty simple. Call the r_implode function as normal, passing to it the ‘glue’ string you wish to employ as well as the array against which to run it.

Have fun.

PHP: Re-index an Array CodeUnit 03 APR 2010

Say you used to have a nice little array which you’ve since gone and hacked to pieces through various merges, and cuttings, etc., resulting is a rather non-uniform, keyed array mess.

Now in order to return to some sort of sanity it might be a good idea to take that input array of yours and retrieve from it a new array containing all the values (currently finding themselves inhabiting the original mess) but with a bright and shiny new, numerically ordered index.

Easy.

Simply make use of the handy PHP array_values function which basically takes an input array, retrieves all values from it and then creates a new array with all those values tucked behind a nice sequential numeric index.

So for example, an array looking like this {a->tomato,b->apple} would now become {0->tomato,1->apple}.

It really is that simple.

Related Link: http://www.php.net/manual/en/function.array-values.php

PHP: Delete all Values to Reuse a Keyed Array CodeUnit 25 MAR 2010

It’s sometimes pretty valuable to reuse array structures if you’re kind of doing a task over and over again, and don’t necessarily want to recreate the array’s keyed structure from scratch with each iteration. In other words, it would be really nice to have a function that automatically sets every element in an array to null but doesn’t actually mess up the array in the process.

Sounds pretty logical and something that most people could use, but believe it or not, no native little PHP function actually exists to do this for us! O.O

Okay, so now that you are over that little bit of shock and horror, let’s quickly whip up some code to do the job ourselves. First, we’ll start be declaring a function that returns a blank or in this case empty string value:

function clearValue($value)
{
	$value = '';
	return $value;
}

Right, the next step is then to apply the handy array_map function we discussed previously in this blog, forcing it to apply our newly created function to the array at hand.

$qsvalues = array_map("clearValue",$qsvalues);

And Bob’s your uncle. The keyed array $qsvalues will now be sitting with a blank string in each and every one of its elements, exactly what we were looking for! :)

How to Apply a Function to Each Value in an Array CodeUnit 23 MAR 2010

Sometimes you wish to apply a certain function, be it a built in PHP function or one of your own creations, to each and every value within a particular array. Now doing this is of course as easy as writing a loop to iterate through an array, perform the function on each retrieved value and then save the updated value back into the array.

Easy, but unnecessary.

You see, PHP comes bundled with a great little function called array_map() that is used to apply a callback function to each and every value contained in the supplied array.

So for example if we wanted to throw strip_tags against an array’s contents, it would look something like this:

$original = array('

Paragraph

', 'Bold'); $new = array_map('strip_tags', $original);

As you would expect, the result of this would be an array containing the words Paragraph and Bold, devoid of all their HTML markup.

Nice!

Related Link: http://www.php.net/manual/en/function.array-map.php