Tag Archives: array

PHP: Get the first Key of an Associative Array Tips, Tricks and Tutorials 16 JUN 2018

I am not completely sure about it, but I somehow don’t think that I’ve ever needed to get the first key of an associative array using PHP before. Sure, a simple problem with a simple solution, but seeing as I needed to Google this one, I’m jotting down the answer here for future reference.

So, our example for the day then: Given the following array, print out the first key.

$months = array(

$result = key($months);
if ($result !== NULL){
echo $result; //this will print 'jan'

The important bits are reset(), which moves the internal array pointer back to the first element of the array, and then key(), which retrieves the index element at the current array position (dictated by the internal pointer).

Simple (when you read the documentation).

UPDATE: As pointed out by one of my readers, if you know you have an array with at least one element in it, you could always just use array_keys($months)[0] as an alternative.

Related Link: reset() | key()

PHP: Return Random Element in Array Programming 06 AUG 2014

A quick and easy PHP code snippet to return a random element from a given array:

$items = array('yellow','green','red');
echo $items[array_rand($items)];

All the hard work is being done by the native array_rand php function. Essentially, array_rand picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

Here is an example picking out two random elements from an array:

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";

Quick and easy.


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

PHP: How to Insert into an Array CodeUnit 11 DEC 2012

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");


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

PHP: Identify the Offset of a Specific Array Element CodeUnit 04 DEC 2012

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"));
    [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.


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

JavaScript: A Simple Function to Return a Sorted and Unique Array CodeUnit 28 OCT 2012

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]) {
    return ret;
//["124", "237", "255", "366"]


PHP: Compare the Keys of an Array and find the Difference Programming 27 FEB 2012

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:

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

print_r(array_diff_key($array1, $array2));

/* Results in:
array(2) { 


JavaScript: How to Implode (Flatten) an Array into a String Programming 17 FEB 2012

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:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

//a few example usages
document.write(fruits.join() + "<br />");
document.write(fruits.join("+") + "<br />");
document.write(fruits.join(" and "));

//the output:
//Banana and Orange and Apple and Mango


JavaScript: How to Explode a String into an Array Programming 13 FEB 2012

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:

var str="How are you doing today?";

//some split usage examples
document.write(str.split() + "<br />");
document.write(str.split(" ") + "<br />");
document.write(str.split("") + "<br />");
document.write(str.split(" ",3));

//the output (',' indicates array boundary)
//How are you doing today?
//H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?


PHP: Simple Method to Implode or Explode Arrays with Keys CodeUnit 21 NOV 2011

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.