Almost unbelievably so, PHP doesn’t actually feature a neatly named insert into array function (to be fair though, it doesn’t have a neatly named remove from array function either!). However, inserting values into an array is actually possible, though to do this we need to make use of the array_splice (remove a portion of the array and replace it with something else) function – in a slightly warped way of course. The more complete manual description: array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] ), with the text: Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied. By leveraging the fact that the function accepts a length input to control just how much of the array gets chopped out, we can in fact insert our new values into an existing array by simply pointing at the required offset in the array where we wish to insert our new values, and make use of a zero length value to ensure that no existing elements get dropped out. In practice: $input = array(“red”, “green”, “blue”, “yellow”); array_splice($input, 3, 0, “purple”); // $input is now array(“red”, “green”, “blue”, “purple”, “yellow”); $input = array(“car”, “truck”, “bus”, “train”); array_splice($input, 1, 0, array(“motorbike”,”taxi”)); // $input is now array(“car”, “motorbike”, “taxi”, “truck”, “bus”, “train”); Nifty. Related Link: http://www.php.net/manual/en/function.array-splice.php
To learn the offset or array key for a specific array element in a given array turns out to be fairly easy, thanks to the extra search parameter that the always useful array_keys (return all the keys or a subset of the keys of an array) function offers us. From the manual description: array array_keys ( array $input [, mixed $search_value = NULL [, bool $strict = false ]] ) – array_keys() returns the keys, numeric and string, from the input array. If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned. Knowing this, we can now find exactly where a specific element sits by simply entering a search value when calling the array_keys function, which in practice would look something like this: $array = array(“blue”, “red”, “green”, “blue”, “blue”); print_r(array_keys($array, “blue”)); /* Array ( [0] => 0 [1] => 3 [2] => 4 ) */ The above example shows us that the array element “blue” appears at offset 0, 3 and 4 in the source array. Nifty. Related Link: http://www.php.net/manual/en/function.array-keys.php

I came across this useful little JavaScript code snippet which given a simple input array, will both sort it and ensure that it contains unique values. If you take a look at the code, you’ll notice that the trick is to first sort the array, and once that has been taken care of by JavaScript’s native sort function, we then loop through the array checking that the previous element doesn’t match the element we’re trying to add. Simple, but works well for very simply arrays which need to be unique in nature (e.g. phone numbers before a batch SMS operation.) function sort_unique(arr) { arr = arr.sort(function (a, b) { return a*1 – b*1; }); var ret = [arr[0]]; for (var i = 1; i < arr.length; i++) { // start loop at 1 as element 0 can never be a duplicate if (arr[i-1] !== arr[i]) { ret.push(arr[i]); } } return ret; } console.log(sort_unique(['237','124','255','124','366','255'])); //["124", "237", "255", "366"] Nifty.

To compare two arrays to see if there is a difference, one often makes use of the array_diff function which takes two arrays, compares array1 against array2 and then returns the difference. Now if you actually want to check for a difference in array keys (say for example you’ve built up two associative arrays of table columns and want to check one table’s structure versus another), you can make use of the array_diff_key function, which acts in a very similar fashion to array_diff except for the part where it compares the keys of the associative input arrays as opposed to the values contained within the arrays. In practice: Nifty.

Coming from PHP, I’m well versed in using the handy implode function to flatten an array into a string, specifying the delimiter character to be used to indicate the border between the flattened array elements. Happily for me, plain old vanilla JavaScript also has this ability built into the language, choosing to call its version of this functionality “join”. From the official definition: The join() method joins all elements of an array into a string, and returns the string. The elements will be separated by a specified separator. If this is ommitted, then the default separator of a comma (,) will be used. A few examples on using join: Useful.

Coming from PHP, I’m well versed in using the handy explode function to force a string into an array, using a specified delimiter character to chop up the string into the little bits that are to be stored in the array. Happily for me, plain old vanilla JavaScript also has this ability built into the language, choosing to call its version of this functionality “split”. From the official definition: The split() method is used to split a string into an array of substrings, returning the new array containing the substrings. It accepts two parameters, namely the separator and the limit, both of which are actually optional by the way. The separator parameter is where you specify the delimiter character (if you omit this, the entire string will be stuffed into a single element array ). The optional limit parameter if set will control the number of splits. A few examples on using split: Useful.
Associative arrays are very useful beasts, because values tied to keys makes it so much easier to build up pseudo objects in that it makes it easier to see which piece of array data refers to what. There are a number of ways to store associative arrays of course, but this particular one below is probably one of the simplest for getting a single string out of a one level array with keys, and then transforming back into its array form when you need to make use of it again. function array_implode_with_keys($array){ $return = ”; if (count($array) > 0){ foreach ($array as $key=>$value){ $return .= $key . ‘||||’ . $value . ‘—-’; } $return = substr($return,0,strlen($return) – 4); } return $return; } function array_explode_with_keys($string){ $return = array(); $pieces = explode(‘—-’,$string); foreach($pieces as $piece){ $keyval = explode(‘||||’,$piece); if (count($keyval) > 1){ $return[$keyval[0]] = $keyval[1]; } else { $return[$keyval[0]] = ”; } } return $return; } If you look at the code above, you will see that we are making use of delimiters here to keep firstly the keys aparts, and secondly the key from its associated value. In this case we are using —- to split the array elements, and |||| to split the key from its value. In other words the resulting string is from the implode function is key1||||value1—-key2||||value2—-key3||||value3. Obviously the explode function just works in reverse.
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’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.
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.
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:
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’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. 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.

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

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 while the foreach functionality is great in iterating through an array and returning the array’s values, sometimes one wishes to also capture the key against which a particular value is stored…
Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under whichever martial arts dojo is closest at the time, and for the most part, simply enjoys life with his amazing wife and daughter.
Oh, and he draws ever now and then too.
This is a collection of things that he has managed to find the time to scribble down since 2007.
Looking for Something?
Jump to Category: