I'm a newbie to programming and PHP learning about two dimensional arrays.
When I run this code below, it just gives me a blank page. When I put an echo in front of the function call like this echo usort($a, 'mysort1');
the page shows me a 1 (I have no idea why).
What I really want to see is the output of the array after it's been sorted.
Doing var_dump($a);
is not what I'm after. how do I show the result of the function?
How? Thanks if you can help.
<?php
$a = array (
array ('key1' => 940, 'key2' => 'blah'),
array ('key1' => 23, 'key2' => 'this'),
array ('key1' => 894, 'key2' => 'that')
);
function mysort1($x, $x) {
return ($x['key1'] > $y['key']);
}
usort($a, 'mysort1');
?>
For starters I think you have two typos in your comparison function:
//should be $y not $x
function mysort1($x, $y) {
return ($x['key1'] > $y['key1']); // Should be $y['key1']
}
Next, usort sorts the array in place returning TRUE on success and FALSE otherwise, that is why you see a 1 when you echo it's return value.
Try:
print_r($a);
to display the sorted array.
Put this as the last line... var_dump($a); it is a quick way to see what is in an array.
Add this:
print_r($a);
after your usort
If you want to output the data nicely using HTML, you could use a foreach loop as follows:
echo "<ul>";
foreach ($a as $key => $value)
{
echo "<li>key: ", $key, " value: ", $value, "</li>";
}
echo "</ul>";
Or something similar with tables if you like.
usort actually sorts the array you pass to it. In other words, it does not return a sorted array but performs the sort on the same array you pass it because it's passing by reference. If you look here: http://php.net/manual/en/function.usort.php you will see there is an ampersand infront of the parameter. The return value of usort indicates success or failure. Again, you can see this in the manual.
Add after the usort line
var_dump( $a );
Your page only prints "1" because it is saying that usort was successful in sorting the array.
You are printing the return value of the function usort , and not the contents of your array. Instead try giving print_r a shot after calling usort.