How to link to a PDF in WordPress

1. Linking to a PDF document from the media library

If you don’t need to display a PDF file, you can use the Media Library. From the post editor, click the “Add Media” button. Upload the PDF file as you would do for an image and click “Insert into post”:

Upload PDF to WordPress

This will create a link with the name of the PDF file as the anchor text. You can modify it if needed.

WordPress - Link to PDF From Media Library

Clicking this link will make your browser open or save the PDF document.
This might be a good enough solution for the occasional PDF file, but if you need to display the content of PDF files within your posts, you’ll need a plugin.

2. Embedding PDF documents into your content

From the WordPress dashboard, go to “Plugins > Add New”. Type “pdf embedder” in the keyword search. Click on “Install Now” and then on “Activate”.

PDF Embedder Plugin for WordPress

From the post editor, insert a PDF file from the media library. The plugin will make a shortcode appear instead of the regular link:

PDF Embedder Shortcode

Preview the post to see the PDF document embedded in the WordPress post:

WordPress PDF Document Viewer

The use of Javascript over Adobe Flash eliminates compatibility issues. The embedded PDF viewer displays a nice toolbar with a page navigator. The premium version of the plugin allows you to customize it if needed.
By default, the viewer width is set to 100%. You can adjust it by appending this to the shortcode:

width="500"

Replace the value with whatever width you want. The shortcode should look something like this:

PDF Viewer Width

You can use the following parameters to customize the toolbar:

  • toolbar = top|bottom
  • toolbarfixed = on|off

If you wish to control the viewer width for mobile devices, you will need the premium version.

Customizing the PDF embedder plugin

To avoid setting the viewer options through the shortcode, you can set these globally. From the WordPress dashboard, go to “Settings > PDF Embedder”.

WordPress PDF Embedder Settings

You can modify the global height and width parameters – along with a bunch of other stuff:

PDF Embedder Viewer Settings

You can change the location of the toolbar, the height of the PDF, and determining how the toolbar appears. You can change these on a case by case basis using shortcodes by referring to the documentation.

Using the PDF Embedder Plugin With a CDN

If you are using a CDN (Content Delivery Network), you will need to do some tweaking. For security reasons, web servers prevent browsers from displaying content from a different source than the website. If you need to embed PDF files hosted on a CDN, you will need to make these changes:
Add this code to the “.htaccess” file located at the root of your website:

<FilesMatch ".pdf">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>

Clear the CDN’s cache and check that the PDF viewer is working. If you are hosting the PDF documents on Amazon S3 or Cloudfront, read the documentation here.

Conclusion

The paid version of the plugin provides additional options such as PDF protection. This allows you to prevent visitors from downloading or printing the original PDF document. Other features include the ability to scroll PDFs continuous scroll and full-screen mode.

But if you can do without the bells and whistles, the base PDF Embedder plugin is a great tool. It’s easy to use and gets the job done.

This is a guest post by Stéphane Brault. Stéphane is a programmer and sysadmin with over 20 years of experience. He specializes in Linux server management and PHP development. He is the owner of WebHostingHero.com, a website providing free tools and tutorials for webmasters.

20 Merry Christmas Royalty-Free Tracks

‘Tis the season to walk in a winter wonderland and go on a sleigh ride. For good reason, it’s one of the most awaited seasons of the whole year.

To keep winter celebrations and holiday-related audiovisual projects joyful and warm, you need the perfect royalty-free music tracks. And while the Internet may be swimming with options, this tutorial helps you find the best ones at AudioJungle. 

1. Christmas 

First up, the royalty-free music track aptly titled ‘Christmas’ (inevitably the first of several). And just like Christmas, this tune has a magical essence to it that’s at the same time cheerful and emotional.

2. Christmas

Let’s say you have a project where you want to display images of a merry and bright time. This song would go great with it, as its use of bells, oboes and strings make it a festive and cheery tune.  

3. Fireworks 

Fireworks are festive. They light up the sky and illuminate the faces of their spectators with a childlike wonder. This track captures what fireworks sound like as they create a pyrotechnic display. 

4. Echoes of Pandora 

The holiday season inspires people to come together and share beautiful moments. And so does this royalty-free music track has that inspirational and epic feel to it. This can fit in beautifully with an emotional scene.

5. Epic Motivational Energetic Upbeat Rock 

The end of the year is a time to party, too! To get your, and your audience’s, dancing feet on the floor,—use this track. ‘Epic Motivational Energetic Upbeat Rock’ gives that surge of energy. 

6. Opening Logo 

For a soft, joyful but very bright approach to holiday music, the ‘Opening Logo’ track. A versatile piece that for holiday projects, for a corporate video or another audiovisual project that requires bright bells in it.

7. Christmas Fun 

Those ultra fun, super upbeat and jazz-inspired Christmas songs are accurately represented in this royalty-free music track. Sleigh bells, trumpets and all of the Christmas staples can be found here. 

8. Fireworks in the Sky 

And because there can never be too many fireworks during the holiday season, this next track of ‘Fireworks in the Sky’ gives a few more options to include the sound of exploding pyrotechnics. 

9. Christmas 

Once again, Christmas makes an appearance in this list (and it won’t be the last one). This tune is the ultimate commercial holiday jingle. You can fit it nicely in any projects related to Christmas, New Year’s Eve or other celebration of the season.

10. Christmas Deck the Halls 

Deck the halls with boughs of holly! This is easily one of the most recognisable Christmas carols out there. Have the audience falalalala-ing along with this symphonic version of the holiday song par excellence.

11. Magical Christmas Night 

The holiday season is magic. With a tune reminiscent of Louis Armstrong’s ‘What a Wonderful World’, this song helps portray some of the softness, wonder and innocence of the winter celebrations. 

12. Corporate Day 

The holiday season, aside from being sweet and tender, is upbeat and up-lifting. To convey that in multimedia projects, use a royalty-free music track such as ‘Corporate Day’. 

13. Dreamy Uplifting and Inspiring Piano With Orchestra 

Dreamy, uplifting and inspiring. Three words that describe the holiday season. Similarly, they describe what this song is about. With flutes, pianos, strings and other instruments, this music track will cheer up everyone. 

14. La La La Song 

Sing-alongs are another staple of the holiday celebrations. This catchy melody with happy-go-lucky lyrics has the right amount of brightness and glee to get your audience clapping and tapping their feet to it.

15. Christmas 

Picture waking up on a cold winter morning. Looking out of the window with a hot cup of chocolate and seeing snow falling outside. This Christmas song is the perfect background music to complement that scene.

16. Christmas 

For a very traditional holiday royalty-free music track, try this Christmas song. Jingling bells accompany a very light and heartwarming tune for holiday cheer in a joyous way.

17. Christmas Sleigh Ride 

The holiday season needs a sleigh ride. With this royalty-free music track, you’ll feel you’re riding along. You may even hear the horse’s hooves stepping on the snow as you’re being ridden around.

18. Ding Dong Merrily on High 

Epic, grandiose, inspiring and merry as can be, this royalty-free music track is all the holiday season is meant to be. It has a powerful orchestra that is joined by a talented and emotional choir. 

19. Romantic Piano 

For a much softer approach to the winter celebrations, this song called ‘Romantic Piano’. The combination of the piano with soft strings will inject a heart-warming feeling to your seasonal audiovisual projects.

20. Falling Snow 

Lastly, the royalty-free music track ‘Falling Snow’. With it, the audience will be able to picture doing all of the traditional activities of the season: sitting by the fire, watching twinkling lights and spending joyful times with loved ones. 

Conclusion

The songs of the holiday season are the background music to some of the happiest and brightest moments in people’s memories. For holiday-related audiovisual projects with that heart-warming and cheerful feeling, check out the selection presented in this tutorial. 

If you don’t find exactly what you need, remember to search through AudioJungle‘s library for the perfect match.

{excerpt}
Read More

3 Simple Tunings Every Recording Guitarist Should Try

There’s an infinite number of guitar tunings beyond the accepted standard of EADGBE. Open G, DADGAD… names that conjure images of slide players and folk aficionados, which some may find off-putting.

Alternate tunings, however, needn’t be baffling. Having command of a few of these help to  broaden one’s usefulness as a player. In this tutorial, I’ll present three simple tunings that require minimum adaption to your current knowledge base.

Starting with the most common.

Drop Tuning

Before you do anything unfortunate, this does not refer to retuning a guitar by letting it fall to the floor.

Drop tuning is taking the lowest string and retuning it down, usually by a tone. For example:

  • Standard Tuning EADGBE
  • Drop Tuning DADGBE

This particular tuning is known as Drop-D.

The Idea Behind This

The biggest attraction is what it does to the three lowest strings. Look again:

DADGBE

This creates a power chord, namely a root note, a fifth note and an octave.

What’s more, the notes are all on the same fret so a single finger is required instead of two or three fingers for standard tuning. This makes moving the shape around far faster.

Another trick is to use the lowest note as a pedal tone, which is a sound played repetitively as a backdrop to other sounds.

A song where you’ll hear both of these traits is Girl All The Bad Guys Want by Bowling For Soup.

Lower and Lower

This isn’t the only possible tuning. Those who favour heavier sounds can tune the entire guitar down and then apply drop tuning.

For example, Alter Bridge’s Isolation is played in Drop-C. This is how you’d arrive at this tuning:

  • Standard Tuning EADGBE
  • D Standard DGCFAD (all notes down a tone from Standard Tuning)
  • Drop C CGCFAD (D Standard with the lowest note down a tone)

We’ve plumbed the depths, let’s go higher.

G Standard

As the name suggests, it’s a derivative of standard tuning as the intervals between strings remain the same. As the lowest note here is G, however, you end up with a completely different tuning.

  • Standard Tuning EADGBE
  • G Standard GCFA#DG

Up or Down

I should point out this involves tuning the guitar up from standard. I wouldn’t recommend doing this with your regular gauge strings, especially if you play 10s or above, as the increased tension may seriously damage the guitar’s neck.

Choose a lighter gauge as this balances the increased pitch of the tuning with the reduced tension of the gauge. I have a guitar in this tuning and I use 7-gauge strings, which are the lightest you can buy. The only caveat is that you’ll need to play more carefully as a lighter gauge means a greater likelihood of breakage.

If you want to tune down to G, then good luck—you’ll need strings like overhead cables to combat the significant loss of tension. The intonation will be practically non-existent and the resultant sound will appeal only to whales and elephants.

No New Knowledge

Don’t forget, this is still a standard tuning. This means that everything you know in standard tuning—chords, scales, arpeggios—all still applies.

The point you must remember is whatever you play in G Standard will sound a minor third above standard tuning.

For example, if you play a G chord in G Standard, the shape you use looks like G but the resultant sound is actually B flat.

Couldn’t I Just Use A Capo?

If you’re re-voicing chords then, yes, you could. However, as soon as you use a capo, you’re reducing the number of frets available. Not only have you cropped the range of the instrument but the highest notes on the guitar remain unchanged.

Using G Standard means you lose a little from the bottom of the guitar’s range but you gain at the top end. 

This is especially useful for soloists. Even electric guitarists struggle to hit the top of the guitar’s range, as the frets get closer together the higher you go. Having a guitar tuned up brings these top notes down the neck, so frets become wider apart and playing becomes easier.

As a session guitarist, I get handed keyboard-composed parts that are beyond the guitar’s range. Eventually, I set up a guitar in G Standard and it’s been in use ever since. I can’t recommend it enough.

Nashville Tuning

Purportedly, the name comes from the usage of this tuning by Nashville session guitarists and was originally a way to simulate the rich chorusing sound of a 12-string guitar.

How it Works

Here’s the good news—it’s exactly the same as standard tuning. So, everything you already know can be played in this tuning as well.

It’s all about the gauge of the strings. Nashville tuning takes the E, A, D, G strings and tunes them up one octave. Now, as mentioned when covering G Standard you can’t take the regular gauge strings and crank them up that far—they’ll either burst or the guitar’s neck will give way.

Instead, replace these four strings with those of a much lighter gauge. Traditionally, this was done by taking the octave strings from a 12-string set. Doing this leaves you with a full set for standard tuning, as well as some spares. 

If this sounds too difficult, you can also buy Nashville Tuning sets.

Six Versus Twelve

If you own a 12-string guitar, you might struggle to see the point of this. That said, Nashville tuning has some key advantages. It’s:

  • Cheaper than owning and maintaining a 12-string
  • Easier to play
  • Kinder to your fingers
  • Electric 12-strings are less common than acoustic ones, limiting your choice of sound. By contrast, Nashville tuning can be played on ANY 6-string guitar

It’s not just about producing a 12-string’s characteristic jangle. Adding a Nashville part to an existing six-string recording creates clarity and richness, lifting it in the mix. Plus, if you capo the Nashville guitar, you’ll have pseudo-mandolin parts.

Conclusion

Alternate tunings can feel like a backward step, as they often involve learning new shapes and patterns. These three tunings are simple, fun, and require little or no new adjustment to your playing.

  • So why not try:Drop tuning for rich lows and pedal tones
  • G Standard for new voicings and increased upper range
  • Nashville tuning for brightness and lift in a mix

{excerpt}
Read More

Comparing the 5 Best PHP Form Builders

If you’re developer using PHP to build a website for yourself or a client, chances are at some point you’ll need to add a form to the site. The most common forms on the average website are contact forms. They enable visitors to contact you quickly and easily. But other forms can come in handy as well. For example, you may want to add a PHP email form as an alternative to the PHP contact form, or add a form to get feedback from your visitors on some aspect of your service or products. Whatever kind of form you need, you’re going to want to have one up and running quickly and easily.

That’s where a PHP form builder comes in. Today we’ll take a look at the five best PHP form builders available at Envato Market and compare them in terms of functionality, flexibility and aesthetic appeal. But first let’s look at exactly what a PHP form builder is.

What is a PHP Form Builder?

A PHP form is a form on a web page that allows visitors to the page to input information and sent it to a server to be processed in some way. In essence, it’s an online version of a paper form where users fill out particular fields and then hand them in to be processed.

A PHP form builder, also known as a PHP form generator, is a tool you can add to your website that enables you to generate a variety of well-designed PHP forms quickly and easily.

Why Should You Use a PHP Form Builder?

The greatest benefit of using a PHP form generator is to speed up the job of creating and adding well-executed forms to your site. The best-designed PHP form generators allow you or your client to create a variety of professionally-designed web forms and add them to a web page quickly and easily. When someone fills out and submits a form, the form builder will they allow the website owner to easily receive notification via a computer or mobile device. They also allow the website owner to collect, browse, or download the data received from the form in an organised and clear way.

Not everyone who needs to add a form to their website wants or needs the same functionality, so the right PHP form generator for you isn’t necessarily the one with the most bells and whistles. Instead, it is the one that best meets your needs.

Comparison of the 5 Best Php Form Builders

Easy Forms: Advanced Form Builder and Manager

Easy Forms PHP form builder checks all the boxes when it comes to the ideal form generator and is the perfect choice for the inexperienced developer. The form builder uses a drag and drop system that allows you to create forms in minutes right from your browser with little coding knowledge, and offers a good selection of themes and templates to appeal to a variety to taste and branding needs.

Easy Forms enables you to create the usual forms you’d expect—like contact
forms, order forms, registration forms and online surveys. But you can
also create specialised forms like multi-page forms and multi-column
forms.

Your forms can then be placed anywhere on your webpage and
once embedded, you can track views, submissions, geographical data,
abandonment rates and other important performance information. What’s
more, Easy Forms offers form analytics to learn more about your data,
the ability to create reports based on the analytics and the ability to
export data collected by your forms.

Additional features:

  • user management
  • geolocation
  • email notification
  • autoresponder
  • mobile friendly
  • and more

User imagesthataspire says:

This is an excellent script and, if you need online forms, will almost certainly meet your needs.

Zigaform PHP Form Builder: Contact & Survey

The Zigaform: Contact & Survey enables you to build a range of forms for any PHP website in a matter of minutes. The builder uses a handy grid system that you can drag-and-drop over 40 form elements into, to create whatever kind of form meets your need. You can use their Skin Customiser and over 700 icons, 650 fonts, 80 animation effects to fine tune every part of your form so that it fits nicely into the webpage on which it’s located.

Once a user has completed a form they receive an acknowledgement email and you receive a notification email, both of which are completely customisable. All data submitted via the Zigaform is stored in the admin panel, where it can be exported from in CSV or PDF from. The builder also allows you to filter and search submitted data which can then be used to create graphic charts for trend and other analysis.

Additional features:

  • extensive documentation
  • translation ready
  • spam protections
  • cross browser compatibility
  • form validation
  • and more

User orlandobcr says:

“I had found the product very useful. Lots of details to customise, lots of options to implement. Nice work!”

Zigaform: PHP Calculator & Cost Estimation Form Builder

The Zigaform: PHP Calculator & Cost Estimation Form Builder is the sister of the Zigaform Contact & Survey Form Builder mentioned above and specialises in helping you to build your own e-commerce and invoicing forms, summary estimate form and instant checkout payment forms that gives your buyers a simplified checkout experience.

Other than these specialised forms, the PHP form generator has the same great features as the Zigaform Contact & Survey Form Builder. You can drag-and-drop the numerous form elements provided into a organising grid and use the Skin Customiser, numerous icons, fonts, and animation effects to customise your form. The builder also offers the same great notification and data processing as its sister form builder.

PHP Form Builder

Additional features:

  • advanced search for entries
  • import and export your custom forms
  • option to duplicate forms and fields
  • detailed entries report by form
  • mobile friendly
  • and more

User davinci7 says:

“This form is absolutely brilliant! I had previously spent more than $400 having a complex form developed for me (in the end it didn’t even work), but I built the same form myself using this software in around 30 minutes. The customer support I received was amazing. I was very reluctant to buy it, but now I can’t recommend it enough.”

PHP Form Builder

A powerhouse of form builders, the PHP Form Builder, allows you to create just about any type of form you need using simple functions. The builder also provides options for horizontal, vertical and inline layouts to suite your page design and accepts any HTML5 form elements, including field sets, multiple selects, opt groups, button groups, etc.

You can customise the HTML with wrappers, IDs, classes and attributes, JavaScript events, and custom code almost anywhere. The builder comes with excellent documentation suitable for both novice PHP users and experienced programmers.

PHP Form Builder

Additional features:

  • build any form with any framework
  • validate posted values
  • send your emails using customisable HTML/CSS templates
  • connect your database and insert, update or delete records
  • over 120+ prebuilt templates included
  • and more

User MonicePetkovska says of this incredible PHP form builder:

“The support is great, I’m really impressed. The product is easy to implement. Thank you again for your support. I’m beginner in PHP and I learned a lot of things from you.”

Aquaria Contact Form Builder 5

The Aquaria Contact Form Builder 5 is the perfect form builder for someone looking for a simple solution to adding contact forms to their websites. A lightweight builder, Aquaria is easy to install and once installed, with one click you can create a PHP contact form that is up and ready to use. The builder offers unlimited colour and over 600 fonts and icons so that you can customise your form to suit your needs.

Aquaria Contact Form Builder 5

Additional features:

  • works on both PHP and HTML pages
  • fully responsive layout
  • CAPTCHA protection
  • supports all major browsers
  • and more

User ar10 says:

“Very customize-able and good customer support!”

Choosing the Right PHP Form Builder For You

From the five PHP form builders covered here, you can see that form builders come in various sizes and functionality. For someone looking for a simple and reliable contact form the Aquaria Contact Form Builder 5 is the right choice, while for someone who needs various kinds of invoicing and e-commerce forms, the Zigaform: PHP Calculator & Cost Estimation Form Builder is a better choice. For someone else who needs a large degree of flexibility in creating a variety of forms the Easy Forms: Advanced Form Builder and Manager will be the best choice.

Source:: Net Tuts

How to Sort Arrays in PHP

It is always easier to grab a specific piece of information from sorted data, otherwise you have to go through each element of the array one at a time. For example, lets say you have stored the score of different students in a class in an array or a table. If the data is not sorted by the scores obtained, you will have to look at the score of each student in the class before you can tell who obtained the highest and lowest score. If the table was already sorted low to high on basis of scores, just looking at the score of first student would tell you the lowest mark.

Sorting makes a lot of tasks that require accessing or obtaining a specific set of data very easy and efficient. In this tutorial, we will learn how to use built-in PHP functions to sort different kinds of array.

Sorting an Array by Value

Sorting an array by the value of its elements is very easy in PHP. You can choose to maintain or discard key-value associations, and you can also define your own functions to dictate how elements are sorted. I’ll show you how in this section of the tutorial.

You can use the sort(&$array, $sort_flags) function to sort the values of an array from low to high. However, it will not maintain any key-value associations when sorting the array. New keys are assigned to sorted elements instead of a simple reordering. The optional second parameter allows you to specify how the elements should be sorted. It can have six different values:

  1. SORT_REGULAR—This will sort the values without changing their types.
  2. SORT_NUMERIC—This will sort the values by comparing them numerically.
  3. SORT_STRING—This will sort the values by comparing them as strings.
  4. SORT_LOCALE_STRING—This will compare the values as string based on the current locale. You can update the locale yourself by using setlocale().
  5. SORT_NATURAL—This will sort the items using “natural ordering” while comparing them as strings.
  6. SORT_FLAG_CASE—This can be combined with SORT_STRING or SORT_NATURAL to turn off case-sensitivity while sorting strings.

Here are a couple of sorting examples to help you quickly grasp the difference between all the sort flags.

<?php

$random_data = [32508, 98134, "234984", "3249832", "38", 123, "Apple"];

sort($random_data);
echo "Regular Sorting  — ";
foreach($random_data as $element) {
    echo str_pad($element, 9)." ";
}
// Regular Sorting  — 38        123       32508     98134     234984    3249832   Apple

sort($random_data, SORT_NUMERIC);
echo "nNumeric Sorting  — ";
foreach($random_data as $element) {
    echo str_pad($element, 9)." ";
}
// Numeric Sorting  — Apple     38        123       32508     98134     234984    3249832

sort($random_data, SORT_STRING);
echo "nString Sorting   — ";
foreach($random_data as $element) {
    echo str_pad($element, 9)." ";
}
// String Sorting   — 123       234984    3249832   32508     38        98134     Apple

In the example, regular sorting, the numerical strings are converted to their numerical values and sorting is done accordingly. The string “Apple” is non-numeric so it is left untouched and compared as a string.

In the second example, numeric sorting, we want the data to be sorted based on numerical value so “Apple” is converted to the numeric value 0 and comes first. Rest of the values are sorted as expected.

In the third example, all the values are treated as strings. This means that instead of comparing the numerical value of 123 or 3249832 with 38, they are compared as strings—one character at a time. Since “1” comes before “3”, the value 123 is considered lower than 38.

If you want to sort your array values from high to low instead of low to high, you can do so with the help of the rsort() function. It accepts all the same parameters as sort() but sorts the values in reverse order. It also doesn’t maintain any key-value associations, so it isn’t a good pick for sorting associative arrays.

Sort an Associative Array

Key value associations become important when you are dealing with associative arrays. Consider the following example where an associative array is used to store the name of different persons and their favorite fruit. If you want to sort the list alphabetically by the name of the fruits, using the sort() function from previous section will result in loss of associated keys.

<?php

$fruit_preferences = ["James" => "Orange", "John" => "Banana", "Patricia" => "Apple", "Jennifer" => "Mango", "Mary" => "Grapes"];

echo "Before Sorting — n";
foreach($fruit_preferences as $person=>$preference) {
    echo $person." likes ".$preference."n";
}

/*
Before Sorting — 
James likes Orange
John likes Banana
Patricia likes Apple
Jennifer likes Mango
Mary likes Grapes
*/

sort($fruit_preferences);

echo "After Sorting  — n";
foreach($fruit_preferences as $person=>$preference) {
    echo $person." likes ".$preference."n";
}

/*
After Sorting  — 
0 likes Apple
1 likes Banana
2 likes Grapes
3 likes Mango
4 likes Orange
*/

?>

As you can see, we not only lost the association of people with their favorite fruits, we also lost the names of the different people. Each sorted value has been assigned a new numeric index based on its position in the sorted array.

To help you tackle this problem easily, PHP has two different functions which maintain key-value association while sorting arrays by their values. These two functions are asort() and arsort(). The following code snippet sorts the same $fruit_preferences array but uses asort() to do so.

<?php

$fruit_preferences = ["James" => "Orange", "John" => "Banana", "Patricia" => "Apple", "Jennifer" => "Mango", "Mary" => "Grapes"];

echo "Before Sorting — n";
foreach($fruit_preferences as $person=>$preference) {
    echo $person." likes ".$preference."n";
}

/*
Before Sorting — 
James likes Orange
John likes Banana
Patricia likes Apple
Jennifer likes Mango
Mary likes Grapes
*/

asort($fruit_preferences);

echo "After Sorting  — n";
foreach($fruit_preferences as $person=>$preference) {
    echo $person." likes ".$preference."n";
}

/*
After Sorting  — 
Patricia likes Apple
John likes Banana
Mary likes Grapes
Jennifer likes Mango
James likes Orange
*/

?>

As evident from the above example, the value Apple moves to the top while still maintaining its association with Patricia. The fruit names could be sorted in reverse just as easily by using the arsort() function.

Both these functions accept the same sorting flags as the value of their optional second parameter as sort() and rsort().

Sorting Array Elements by Value with User-Defined Functions

The four sorting functions can easily handle your common sorting needs with the help of different flags. However, sometimes your criteria for comparing the array elements might be different.

Lets say you have an array of random words which need to be sorted alphabetically. However, you also want to sort them based on their length before sorting them alphabetically. For example, zoo would come after apple in traditional alphabetical sorting. However, if want to show the short words before longer ones, zoo will appear before apple. In the same set of letters, ape would come before zoo due to alphabetical ordering.

Basically, the words are first sorted based on their length and then the words with same number of letters are sorted alphabetically within their own group. This type of sorting is not built into PHP so we will have to write our own sorting function.

What PHP does in this case is provide you a couple of functions which can be used to pass the array that you want to sort along with the name of your own sorting function.

You can use the usort() function to sort array values in regular arrays. Similarly, you can use the uasort() function to sort values in associative arrays while also maintaining key-value associations.

The code snippet below shows one way of accomplishing this behavior.

<?php

$random_words = ["ape", "apple", "zoo", "pie", "elephant", "banana", "picnic", "eye"];

sort($random_words);
echo "Regular Sort Function: n";
foreach($random_words as $element) {
    echo str_pad($element, 9)." ";
}

/*
Regular Sort Function: 
ape       apple     banana    elephant  eye       picnic    pie       zoo
*/

function custom_sort($word_a, $word_b) {
    if (strlen($word_a) < strlen($word_b)) {
        return -1;
    }
    if (strlen($word_a) == strlen($word_b)) {
        return strcmp($word_a, $word_b);
    }
    if (strlen($word_a) > strlen($word_b)) {
        return 1;
    }
}

usort($random_words, "custom_sort");
echo "nCustom Sort Function: n";
foreach($random_words as $element) {
    echo str_pad($element, 9)." ";
}

/*
Custom Sort Function: 
ape       eye       pie       zoo       apple     banana    picnic    elephant
*/

?>

In the callback functions meant for custom sorting, we have to return an integer less than 0 to indicate that the first value is smaller than the second. Return 0 if the first value is equal to the second. Return an integer greater than 0 if the first value is greater than second.

Since our primary sorting criteria was string length, we directly return -1 if the first word is shorter than the second. Similarly, we directly return 1 if the first word is longer than the second. If the two words are equal in length, we compare them alphabetically using the strcmp() function and return its value.

As you can see in the output, our custom sort function reorders the words exactly the way we wanted.

Sorting an Array by Key

Sorting an array based on its keys is generally useful when you are dealing with associative arrays. For instance, you might have an array with information about the total number of airports in various countries. Assuming that the names of different countries are keys and the number of airports are values, you might want to sort the country names alphabetically. This is very easy to do with functions ksort() and krsort(). Both these functions will maintain the key-value association of array elements after sorting. The function ksort() sorts the keys from low to high and krsort() sorts the keys from high to low.

Here is a basic sorting example:

<?php

$airport_count = ["United States" => 13513, "Brazil" => 4093, "Mexico" => 1714, "Canada" => 1467, "Russia" => 1218, "Argentina" => 1138, "Bolivia" => 855, "Colombia" => 836, "Paraguay" => 799, "Indonesia" => 673];

ksort($airport_count);

foreach($airport_count as $country=>$count) {
    echo str_pad($country, 15)." ".$count."n";
}

/*
Argentina       1138
Bolivia         855
Brazil          4093
Canada          1467
Colombia        836
Indonesia       673
Mexico          1714
Paraguay        799
Russia          1218
United States   13513
*/

?>

You can also provide PHP without your own custom function for sorting array keys using the uksort() function. Just like usort(), the callback function in uksort() also requires you to return an integer less than 0 if first key is considered less than the second one and an integer greater than 0 if first key is greater than second. This function also maintains the key-value association of array elements.

<?php

$airport_count = ["United States" => 13513, "Brazil" => 4093, "Mexico" => 1714, "Canada" => 1467, "Russia" => 1218, "Argentina" => 1138, "Bolivia" => 855, "Colombia" => 836, "Paraguay" => 799, "Indonesia" => 673];

function custom_sort($word_a, $word_b) {
    if (strlen($word_a) < strlen($word_b)) {
        return -1;
    }
    if (strlen($word_a) == strlen($word_b)) {
        return strcmp($word_a, $word_b);
    }
    if (strlen($word_a) > strlen($word_b)) {
        return 1;
    }
}

uksort($airport_count, "custom_sort");

foreach($airport_count as $country=>$count) {
    echo str_pad($country, 15)." ".$count."n";
}

/*
Brazil          4093
Canada          1467
Mexico          1714
Russia          1218
Bolivia         855
Colombia        836
Paraguay        799
Argentina       1138
Indonesia       673
United States   13513
*/

?>

In the above example, we have used the custom sort function from the previous section to sort name of countries first by the length of their name and then alphabetically.

Sorting Multi-Dimensional Arrays in PHP

It is much more common in real life to deal with multi-dimensional information. For instance, institutions will store the marks of all students in a variety of subjects in a single table instead of creating new tables for each subject. If you have to store the same information in PHP, you would also prefer to do it using a multi-dimensional array instead of separate array for each subject.

In this tutorial, we will learn how to sort a multi-dimensional array using a list of tallest buildings in the world as example. Our array will contain information about the name of the building, the city and country where it is located, number of floors and total height in meters along with the year in which it was built.

When you want to sort the values in a multi-dimensional array based on the a particular field, you can simply use the usort() function. The example below should help you understand this technique better.

<?php

$tallest_buildings = [
    ["Building" => "Burj Khalifa","City" => "Dubai","Country" => "United Arab Emirates","Height" => 828,"Floors" => 163,"Year" => 2010],
    ["Building" => "Shanghai Tower","City" => "Shanghai","Country" => "China","Height" => 632,"Floors" => 128,"Year" => 2015],
    ["Building" => "Abraj Al-Bait Towers","City" => "Mecca","Country" => "Saudi Arabia","Height" => 601,"Floors" => 120,"Year" => 2012],
    ["Building" => "Ping An Finance Center","City" => "Shenzhen","Country" => "China","Height" => 599,"Floors" => 115,"Year" => 2017],
    ["Building" => "Lotte World Tower","City" => "Seoul","Country" => "South Korea" ,"Height" => 554,"Floors" => 123,"Year" => 2016]
];

function storey_sort($building_a, $building_b) {
    return $building_a["Floors"] - $building_b["Floors"];
}

usort($tallest_buildings, "storey_sort");

foreach($tallest_buildings as $tall_building) {
    list($building, $city, $country, $height, $floors) = array_values($tall_building);
    echo $building." is in ".$city.", ".$country.". It is ".$height." meters tall with ".$floors." floors.n";
}

/*
Ping An Finance Center is in Shenzhen, China. It is 599 meters tall with 115 floors.
Abraj Al-Bait Towers is in Mecca, Saudi Arabia. It is 601 meters tall with 120 floors.
Lotte World Tower is in Seoul, South Korea. It is 554 meters tall with 123 floors.
Shanghai Tower is in Shanghai, China. It is 632 meters tall with 128 floors.
Burj Khalifa is in Dubai, United Arab Emirates. It is 828 meters tall with 163 floors.
*/

?>

In the above example, the information about each building is stored in its own array inside the main $tallest_buildings array. The storey_sort() function simply subtracts the numbers of floors in the second building from the first to determine which building is smaller according to our criteria. We don’t have to worry about returning a specific negative or positive value because all negative values mean smaller and all positive values mean bigger.

In the end, we just iterate through the main array and print out information about each building.

Final Thoughts

In this tutorial, I showed you some different functions in PHP which can be used to sort arrays either by their keys or their values. We also learned how to sort an array by its keys or values using our own custom sorting criteria with the help of uksrot() and uasort() functions. The final section discussed how to sort all the values in a multi-dimensional array using only a specific field.

I hope you learned something new from this tutorial. If you have any questions or suggestions please let me know in the comments. The best way to learn is to try and create some examples of your own, sorting arrays by using these functions.

Source:: Net Tuts