Smiley Happy Coder

Simple method to test if a key exists in a multidimensional array.

I’ve used this function/method a few times over the years so I thought I’d jot it down to save future me some headaches.

Sometimes I have needed to check an array to see if the key exists within it. One solution might be to just check if that key is set.

if ( isset( $array['key'])) {

The issue with this method is that I might not know what the key is called or even if it exists at the top level of the array. It could be a multidimensional array, it might not be.

So I wrote a wee function to help out. In this case I’m in a Laravel project so its a public static function in a Helpers repository.

You’ll see that the first thing that goes on is to check if the key exists at the top level of the array, if found the function will return. No sense battling on if we already have our answer.

The second thing I do is to loop over the items in the array and, should that item be an array, perform that same test and return, if nothing is found then return false.

I could have abstracted the ‘array_key_exists’ chunk off to a different method to dave duplication but I feel thats just a step too far.

/**
 * Simple method, pass a key then the array
 * Method will return a bool
 * 
 * @param $key
 * @param $array
 *
 * @return bool
 */
public function testIfKeyExistsInArray( $key , $array )
{
    if ( array_key_exists ($key, $array) ) {
        return true;
    }

    //If the item is an array, then dig into it...
    foreach( $array as $item ){
        if ( gettype($item) === 'array'){
            if ( array_key_exists($key , $item)){
                return true;
            }
        }
    }

    return false;
}

Example usage

if ( Helper::testIfKeyExistsInArray( 'add_another' , $request->all() )){
    //Do whatever here
}

Limitations

The isn’t a very intelligent method by any means, it literally just looks one level deep if the item is an array.

I’m 100% sure there are many many ways to skin this cat. But this does work.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Running Laravel on a shared host, Ultimate guide!

Some time ago I wrote about running Laravel on a shared host and some tips and tricks for getting it running right.

Well recently I had cause to revisit the problem and get it running once again.

My server setup

When I create the new site, in my case it was a subdomain, on my server all I get is a folder. That’s it, a folder.

/subdomains/subdomain-name

Well as you can imagine this is pretty useless. Laravel like most PHP based systems these days keep their app type files above the public folder and rightly so in an ideal world. In my case I want it to work from the single folder.

Steps to take

  1. Redirect all traffic from the root folder to the public folder
  2. Include the subdomain-name/public/index.php from subdomain/index.php

Redirecting all traffic

Inside the root of the subdomain folder, so in my case /subdomains/subdomain-name I created a new .htaccess file with the following contents.

RewriteEngine On RewriteBase

RewriteCond %{THE_REQUEST} /public/([^\s?]*) [NC] RewriteRule ^ %1 [L,NE,R=302]

RewriteRule ^((?!public/).*)$ public/$1 [L,NC]

This simply redirect any traffic that comes in to the public/index.php

However there is an issue with this, it only works if there is a parameter passed for example the visitor has browsed to site.com/something If a visitor browses directly to the website then this won’t work! On to step 2…

Including the index file.

In the root folder open or create a file called index.php, inside that file paste the following code.

<?php

include_once('public/index.php');

This include then makes php act as if the request has indeed landed inside the public folder.

I hope this is of help to someone to get up and running with Laravel on a shared host.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Tweet the highlighted text using Tweetbot and Keyboard Maestro

I have tinkered somewhat recently with Keyboard Maestro and in particular the ability to Tweet the highlighted text. I knew I could do this with Keyboard Maestro but it was a little bit of a learning process.

But why Tweet the highlighted text at all?

When I find something I like, a quote or a link to something interesting I’d quite like to easily post it. So I created my Tweet the highlighted text macro.

It looks like this Tweet the highlighted text

What does it do?

It quite simply performs a copy, to get the highlighted text into the clipboard. Then, similarly to my last macro, it opens Tweetbot and opens the new tweet dialogue. Once that’s open then Keyboard Maestro performs a paste.

One thing of note. I disabled the very last action which was to actually submit the Tweet. I found through using the macro that I often want to comment on the link so whatever.

Here’s a link to the macro on GitHub

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Getting HTML form data to PHP array

How many times have you built a HTML form that has an indefinite number of fields? Maybe a list of categories for example. Ultimately you want those in a PHP array so you can parse them later on. Well thankfully thats pretty gosh darned easy but its a nice little trick I picked up a while ago.

Lets imagine we have a list of fields where the user can enter a name for each category. You might have a button that when clicked a chunk of JavaScript will drop a new form input onto the end of the list.

Read On >

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Importing into MySQL using Source

I recently found the Source command for MySQL. When importing .sql files into MySQL the normal way would be to run the following command from outside of MySQL

mysql -u username -p databasename < filename.sql

This is a great command but sometimes the file size is just too large for this command to handle. I haven’t looked into why that is however, I have found a solution.

The Source Command

Source Command

This command appears to loop through the file line by line rather than try to import the whole file as one. However it works, works is the key work here 🙂

The Syntax

source /var/www/filename.sql

It is important to note that this is a MySQL command rather than a linux command which means you must already be logged into MySQL.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Simple way to humanise files sizes in PHP

This is just a very quick post to show something I’ve just been working on.

I came upon the need to display file sizes in a human readable way. The PHP method FILESIZE returns the size of the file in bytes. You might see a file size of 1500 or even 23462966. Now what do that mean to the average user? Nothing, so lets humanise it.

The function to humanise files sizes

private function humaniseBytes($bytes , $precision = 2)
{
    //Get the length of the string
    $length = strlen($bytes);

    if ($length <= 3){
        return $bytes . 'B';
    } elseif( $length > 3 && $length < 7){
        return number_format($bytes / 1000 , $precision) . 'KB';
    } elseif( $length > 6 && $length <10 ){
        return number_format($bytes / 1000000 , $precision) . 'MB';
    } elseif ( $length > 9 && $length < 13){
        return number_format($bytes / 1000000000 , $precision) . 'GB';
    } elseif ( $length > 12){
        return number_format($bytes / 1000000000000 , $precision) . 'TB';
    }
}

The first thing you’ll note are the parameters passed, obviously the $bytes are passes as well as a variable called $precision. This variable just determines the decimal places that should be returned from the number_format function.

I then just simple loop through and find the length and divide by whatever I need to in order to move the decimal place correctly.

Some functions you might see calculate based on the actual file size, my method however uses the string length. Now I will say that this might not be the most accurate solution since a KB isn’t actually 1000 bytes but rather 1024 bytes.

I hope this helps someone out there.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Post a new Tweet from anywhere via Tweetbot using Keyboard Maestro

I’ve long heard of all the great things that Keyboard Maestro can do. I’ve wanted to play with it for absolutely ages, so I started to tinker.

The first thing I decided to create was a method to post a new tweet from anywhere within the operative system. New tweet with tweetbot

So what does this workflow achieve?

We’ll put simply, to create a new tweet I have to work through a couple of steps.

  • Open Tweetbot
  • Click to the “New Tweet” button or menu item
  • Start typing
  • Click “Tweet” or type “Cmd” Return”

I don’t want to waste the time and in all honestly it prevents me from tweeting things because I just won’t move away from what I’m doing.

Often when I want to tweet it’s something that just crossed my mind. I don’t want to wander away from what I’m doing, I just want to post the Tweet as fast as I can.

My macro will, really quickly, switch to Tweetbot and open the new Tweet dialogue.

Heres what it looks like

New Tweet Macro

So, by typing “newtweet” absolutely anywhere within the operative system the macro is fired.

Link to macro on GitHub

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Prevent screen output from bash scripts

More recently I’ve been working on a few bash scripts that do repetitive tasks for me. One such script will build a new development web server and install various bits of software so that I can get working really fast. One of the things I dislike is the screen output of these scripts. It often looks like a massive mess and since I’ve been planning to release some of these scripts into the wild, a mess just wont do!

Screen Output

I read a lot about preventing screen output and I tested a lot of things I found but I think I’ve come across about the best solution. And let me just point out, its not, by any means, perfect.

I’ve talked before about piping command line outputs to different apps, for example my recent post on the Sublime Text command line tool

The best solution

It seems the best solution is to try to pipe the output to somewhere else. One solution I came up with was to pipe the screen output to a new file and then remove that file. But that feels somewhat hacky, however it does work.

The solution I have been using is to pipe the screen output to /dev/null So something like this.

git clone http://path-to-repository . | /dev/null

Since the path /dev/null doesn’t exist then nothing happens.

Caveat: I have found a few commands that seem to ignore this and just give the screen output regardless. As I said, its not perfect.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Add empty element to Laravel dropdowns

Laravel’s Eloquent is an amazing bit of kit, I personally feel its one of Laravel’s top attributes. It just make life so simple and writing code a pleasant experience. For instance generating Laravel dropdowns is a snap. I’ve written about it before

Laravel dropdowns

Using the lists() method works really well and gives you a nice collection containing the ID and name of the record. I normally build my Laravel dropdowns something like this.

return User::select('name', 'id')
                    ->lists('name', 'id');

Sometimes you might find a situation whereby you need an empty row at the start of the collection. I found a way to achieve this in a previous post. this method relies on concatenating an array to the beginning of the collection inside the blade view. Like this.

{{ Form::select('user', 
array('default' => 'Please select a user') + $users , 
null ) }} 

While this works it feels a bit nasty. So I looked for a better solutions and today I discovered another of Eloquent’s hidden gems.

The Prepend Method

The prepend method allows you to “Push an item onto the beginning of the collection.” It accepts two parameters, a value and key however the key is not required.

In my case it looks like this.

return User::select('name', 'id')
                    ->lists('name', 'id')
                    ->prepend('Please select a user');

And now the output looks like this, just what I needed.

0 => "Please select a user"
1 => "Jayne"
2 => "Amanda"
Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Edit your spelling dictionary on OSX

If you’re anything like me, you quite often type words that aren’t “dictionary” words. OSX will automatically try to correct the “typo” unless you have Autocorrect turned off I’ve previously written about that. The operating system stores your custom words in its own spelling dictionary. Here’s how to edit that dictionary.

OSX stores your custom dictionary items in a text file, this file is hidden away within the operating system. As far as I am aware there is not a GUI interface where you can update the dictionary so here are a couple of ways you could make changes.

The spelling dictionary file exists in the users library file. The path to that file is:-

~/Library/Spelling/LocalDictionary

Via “THE TERMINAL”

I know this puts people off so if you’re not into playing terminals then check out the finder method

Step 1

Open a new Terminal window.

Step 2

Open the file in your editor of choice. Mine is generally nano but if you have sublime and have the shortcut setup then feel free to use that.

Enter the following command

nano ~/Library/Spelling/LocalDictionary

Or this if you have sublime text set up

subl ~/Library/Spelling/LocalDictionary

Step 3

Add your new words. Each new word should be on its own line.

Step 4

Save and close the file.

Or as I said, you could choose to use the Finder method.

Via the Finder

Editing your spelling dictionary can just as easily be done via the terminal

The Library folder is one of those places that Apple doesn’t want you to go. I can understand why as it could be quite easy to cause damage to your user account.

Step 1

Open a new finder window

Step 2

From the menu, choose the “Go” menu and then the “Go to Folder” option. Finder, Go to folder to find spelling dictionary

Step 3

In the popup window, enter the following path

~/Library/Spelling

and click “Go” Go to folder dialogue to find spelling dictionary

Now you will see something similar to this Spelling Dictionary Folder

Step 4

Open the “LocalDictionary” file with Text Edit or your editor of choice. You should see something like this Spelling dictionary LocalDictionary File

Step 5

Add your new words. Each new word should be on its own line.

At this juncture its only fair to point out that the operating system will try to autocorrect whatever you type, so be aware and make sure the entry is correct.

Save and then close the file and your changes should start to work.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Using Sublime Text 3 command line access

If you use Sublime Text 3 and you use the Terminal on OSX then you might want to enable the Sublime Text 3 command line tool. This will enable you to really quickly open a file or folder in Sublime Text 3 straight from the terminal.

Read On >

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Turn spelling autocorrect off on Mac OSX

Having the whole operating system autocorrect your spelling as you type is fantastic. Except when its not.

Read On >

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top