<?php
bool ksort ( arr &$array [, int $sort_flags = SORT_REGULAR ] )
where,
&$array = The input ARRAY
$sort_flags = To control de sorting behavior
( SEE the below TABLE )
?>
CONSTANT | VALUE | OBSERVATIONS | DEFAULT |
SORT_REGULAR | 0 | compare items normally (don't change types). |
SORT_REGULAR |
SORT_NUMERIC | 1 | compare items numerically | |
SORT_STRING | 2 | compare items as strings | |
SORT_LOCALE_STRING | 5 | compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale. |
|
SORT_NATURAL | 6 | compare items as strings using "natural ordering" like natsort. | |
SORT_FLAG_CASE | 8 | can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively | |
ed48 |
<?php
$arr01s = ["x", "Z", "a", "y", "B", "k"];
echo '<pre>';
var_dump($arr01s);
echo '</pre>';
if(ksort($arr01s) == true)
{
echo '<pre>';
var_dump($arr01s);
echo '</pre>';
}
?>
<?php
$arr02s = ["R" => 'red', "G" => 'green', "B" => 'blue',
"H" => 'HUE', "S" => 'SATURATION', "K" => 'BLACK'];
echo '<pre>';
var_dump($arr02s);
echo '</pre>';
if(ksort($arr02s, SORT_STRING) == true)
{
echo '<pre>';
var_dump($arr02s);
echo '</pre>';
}
?>
<?php
$arr03s = ["São Paulo" => 'SP', "Santo André" => 'SP',
"Maceió" => 'AL'];
echo 'The given ARRAY:<br><pre>';
var_dump($arr03s);
echo '</pre>';
setlocale(LC_ALL, 'pt_BR', 'pt-BR');
if(ksort($arr03s, SORT_LOCALE_STRING) == true)
{
echo 'The resulting ARRAY:<br><pre>';
var_dump($arr03s);
echo '</pre>';
}
?>
<?php
$arr04s = [ 'PI' => M_PI, 'PHP_INT_MIN' => PHP_INT_MIN ];
echo 'The given ARRAY:<br><pre>';
var_dump($arr04s);
echo '</pre>';
setlocale(LC_ALL, 'pt_BR', 'pt-BR');
if(ksort($arr04s, SORT_LOCALE_STRING) == true)
{
echo 'The resulting ARRAY:<br><pre>';
var_dump($arr04s);
echo '</pre>';
}
?>
<?php
/*
* Testing ksort() by providing arrays
* with key values for $array argument
* with following flag values.
* 1.flag value as default
* 2.SORT_REGULAR - compare items normally
* To test the new keys for the
* elements in the sorted array.
*/
$various_arrays = array(
array(5 => 55, 6 => 66, 2 => 22, 3 => 33, 1 => 11),
array ("fruits" => array("a" => "orange",
"b" => "banana",
"c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
),
array(1, 1, 8 => 1, 4 => 1, 19, 3 => 13),
array('bar' => 'baz', "foo" => 1),
array('a' => 1,'b' => array('e' => 2,
'f' => 3),'c' => array('g' => 4),'d' => 5),
);
$count = 1;
echo "Various arrays with key values:";
foreach ($various_arrays as $array) {
echo "<br><br>Iteration: $count<br>";
echo "<br>With Default sort flag<br>";
$temp_array = $array;
var_dump(ksort($temp_array) );
echo '<br>';
var_dump($temp_array);
echo "<br><br>Sort flag = SORT_REGULAR<br>";
$temp_array = $array;
var_dump(ksort($temp_array, SORT_REGULAR) );
echo '<br>';
var_dump($temp_array);
$count++;
}
?>