Array Searcher Function

Here’s a simple function that’s very useful. I get the feeling that there’s an probably inbuilt PHP function that already does this, but I can’t find it anywhere if it does exist, so I made one! (If it does exist, please let me know!)

Let’s say you have a 2D array, for example file type descriptors and real english titles, like so:

$allowed_types = array(
    array('application/pdf', 'Adobe PDF'),
    array('application/msword', 'Microsoft Word'),
    array('application/', 'Microsoft Excel'),
    array('application/', 'Microsoft Powerpoint'),
    array('application/zip', 'ZIP file'),
    array('image/gif', 'GIF Image'),
    array('image/jpeg', 'JPEG Image'),
    array('image/png', 'PNG Image'),
    array('image/tiff', 'TIFF Image'),
    array('text/plain', 'Plain text'),
    array('text/richtext', 'Rich text')

…and you want to search for a descriptor and return a real english response. Like so:

function arraySearcher($element, $array){
    foreach ($array as $value){
        if ($value[0] == $element){
            return $value[1];
    return 0;

and so…


…would return…

'Adobe PDF'



…would return 0.

So you can use this function to both look up the description from the file type string (which you get in the $_FILES array when uploading a file) and to check whether something’s in the list. For example:

$file_type = arraySearcher('application/pdf', $allowed_types);
if ($file_type == 0){
    echo "I don't know that filetype.";
} else {
    echo "That is a $file_type";

…gives you…

That is a Adobe PDF.

Ok, so the grammar’s not perfect, but it you get the point.

(Note: of course if you were actually checking a file type on upload you’d want to check the file extension as well… This isn’t a tutorial on security!)


About Mr Chimp

I make music, draw pictures, browse the internet, programme, and make sweet, sweet cups of tea until the early hours.
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

3 Responses to Array Searcher Function

  1. Skilldrick says:

    This is very similar to a question I asked on Stackoverflow yesterday… seriously, get out of my head!

    Btw, loving the blog description!

  2. Mr Chimp says:

    Haha! That’s just weird!

    I’d highly recommend starting a blog like this and writing down whatever new things you discover. It’s really helpful to have something to refer back to that’s in your own words that you can find without having to search the internets for hours (again)!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s