D
dman_2007
Guest
Here's the code demonstrating various ways in which you can specify callback functions in php, i will discuss them each in my next post :
Output produced by the code given above :
Code:
<?php
function sort_function($a, $b)
{
if($a < $b)
{
return -1;
}
else if($a == $b)
{
return 0;
}
else
{
return 1;
}
}
class TestClass
{
public function sort_method($a, $b)
{
if($a < $b)
{
return -1;
}
else if($a == $b)
{
return 0;
}
else
{
return 1;
}
}
public static function static_sort_method($a, $b)
{
if($a < $b)
{
return -1;
}
else if($a == $b)
{
return 0;
}
else
{
return 1;
}
}
}
$array1 = array(3, 1, 5, 23, 11, 17, -3);
$array2 = array(3, 1, 5, 23, 11, 17, -3);
$array3 = array(3, 1, 5, 23, 11, 17, -3);
$array4 = array(3, 1, 5, 23, 11, 17, -3);
print_r($array1);
echo '<br />';
usort($array1, 'sort_function');
print_r($array1);
echo '<br />';
print_r($array2);
echo '<br />';
usort($array2, array(new TestClass(), 'sort_method'));
print_r($array2);
echo '<br />';
print_r($array3);
echo '<br />';
usort($array3, array('TestClass', 'static_sort_method'));
print_r($array3);
echo '<br />';
print_r($array4);
echo '<br />';
usort($array4, create_function('$a, $b', '
if($a < $b)
{
return -1;
}
else if($a == $b)
{
return 0;
}
else
{
return 1;
}'));
print_r($array4);
echo '<br />';
?>
Output produced by the code given above :
Array ( [0] => 3 [1] => 1 [2] => 5 [3] => 23 [4] => 11 [5] => 17 [6] => -3 )
Array ( [0] => -3 [1] => 1 [2] => 3 [3] => 5 [4] => 11 [5] => 17 [6] => 23 )
Array ( [0] => 3 [1] => 1 [2] => 5 [3] => 23 [4] => 11 [5] => 17 [6] => -3 )
Array ( [0] => -3 [1] => 1 [2] => 3 [3] => 5 [4] => 11 [5] => 17 [6] => 23 )
Array ( [0] => 3 [1] => 1 [2] => 5 [3] => 23 [4] => 11 [5] => 17 [6] => -3 )
Array ( [0] => -3 [1] => 1 [2] => 3 [3] => 5 [4] => 11 [5] => 17 [6] => 23 )
Array ( [0] => 3 [1] => 1 [2] => 5 [3] => 23 [4] => 11 [5] => 17 [6] => -3 )
Array ( [0] => -3 [1] => 1 [2] => 3 [3] => 5 [4] => 11 [5] => 17 [6] => 23 )