Tag Archives: associative 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: 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) { 


PHP: A Quick Way to Break up a URL into usable Pieces CodeUnit 27 JAN 2012

PHP has a built in function which allows for the quick breaking up of a well formed URL into usable pieces, namely parse_url.

This function parses a URL and returns an associative array containing any of the various components of the URL that are present. It is important to note that parse_url does not validate the given URL, it simply breaks it up into parts. Partial URLs are also accepted, and whilst parse_url tries its best to parse them correctly, it may return -1 if the URL provided is too malformed.

So what exactly does it break an URL up into then?

Well, given an URL like below, parse_url would return the following:

$url = 'http://username:password@hostname/path?arg=value#anchor';


echo parse_url($url, PHP_URL_PATH);

The output:

    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor


So pretty useful if you want say just the host or query value from a given URL then!

Another thing to note is that it is not designed to work with relative URLs, meaning that you do need to provide it with fully qualified URLs in order to get something usable back.

Still, a pretty nifty little function to keep in mind when writing parsing scripts…

Related Link: http://www.php.net/manual/en/function.parse-url.php

PHP: How to Sort Your Array but Keep Your Keys CodeUnit 06 APR 2010

PHP comes bundled with a range of nifty array sorting functions the simplest of which will simply take your array and sort it either alphabetically or numerically, acting on the array object itself rather than creating a new, sorted object.

But if you have an associative array, in other words an array with keys, running the sort() function might give you a little shock once it has finished executing – if you check out your array, you’ll notice all of your precious array keys have been completely wiped out, obviously not the greatest of lessons to be learned.

In order to get around this, PHP gives us the asort() function which sorts the values contained in an array accordingly, but at the same time retains all of the original value keys. Similarly, the arsort() function sorts the array in the reverse direction, once again saving the original keys.

(If however you wish to sort on the keys of an array, you can look towards ksort() which literally sorts an array according to its keys and not the values it contains!)

You’ll note that while all these sort functions accept a first parameter which is the actual array to sort, they also come with a secondary, optional parameter which allows you to set just how the array is to be sorted. The following sorting options are available to you: