PHP Questions Home
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

How do I write my own sort function?


In PHP you will, in most cases, be able to get by with one of the default sort functions, perhaps used in conjunction with each other.

However there will be times where you want to sort based on some other factor.

When you need to do this, you use the user sort function within PHP, which looks like this usort(array,function) where you specify the user-defined function that will sort the array.

Here is a simple example I've whipped up using a user-defined function to sort an array based on the length of the values, which is useful if you want to find the longest word in an array, for example.

<?php
$inputwords 
= array("whichever","word","is","the","longest","will","appear","at","the","top");
usort($inputwords"sortlen");
print_r($inputwords);

function 
sortlen($a,$b) {
$lena strlen($a); $lenb strlen($b);
if (
$lena == $lenb) return 0;
return (
$lena $lenb) ? -1;
}
?>


This prints the following:

Array
(
[0] => whichever
[1] => longest
[2] => appear
[3] => word
[4] => will
[5] => top
[6] => the
[7] => the
[8] => at
[9] => is
)

Just for completeness, let's reverse from symbol to sort with the shortest value in the array at the top:

<?php
$inputwords 
= array("whichever","word","is","the","shortest","will","appear","at","the","top");
usort($inputwords"sortlen");
print_r($inputwords);

function 
sortlen($a,$b) {
$lena strlen($a); $lenb strlen($b);
if (
$lena == $lenb) return 0;
return (
$lena $lenb) ? -1;
}
?>


Which prints this:

Array
(
[0] => is
[1] => at
[2] => top
[3] => the
[4] => the
[5] => word
[6] => will
[7] => appear
[8] => shortest
[9] => whichever
)



ASK A QUESTION

More arrays PHP Questions

How can I check if a value is already in an array?

How can I display a 2 dimensonal array?

hi, i am querying the DB as follows: $result=mysql_query("SELECT name,items FROM mytable WHERE user_id='$id'"); now,i want to create an array to insert the values that are as a result of this query e'g let's say this is the resultant data: n

How to get most repeated value in an array?

i need to store a multi-dimensioned array into a file. there is plenty of info. on creating md-arrays but i cant find anything on writing a md-array to a file.



Custom Search