Jump to: navigation, search

Php ksort

From w3cyberlearnings

Contents

PHP function ksort

This function sorts array by the array keys.

Syntax ksort

  • array: array input
  • sorttype (optional):
    • SORT_REGULAR (Default- sort the array as it is)
    • SORT_NUMERIC (Sort array use numerical order)
    • SORT_STRING (Sort array as it is string)
    • SORT_LOCALE_STRING (Sort array as string based on local settings)
ksort(array, sorttype);

Example 1

<?php

$name_s = array(
	 'Clair' => 3,
	 'John' => 1,
	 'Alex' => 100,
	 'Blair' => 301
);

ksort($name_s);
print_r($name_s);
?>

Output

Array
(
    [Alex] => 100
    [Blair] => 301
    [Clair] => 3
    [John] => 1
)

Example 2: Default sort

<?php

$name_s = array(
	 'file1' => 3,
	 'file3' => 1,
	 'file100' => 100,
	 'file10' => 100,
	 'file11' => 300,
	 'file9' => 301
);

ksort($name_s);
print_r($name_s);
?>

Output

Array
(
    [file1] => 3
    [file10] => 100
    [file100] => 100
    [file11] => 300
    [file3] => 1
    [file9] => 301
)

Example 3: Sort numeric

<?php

$name_s = array(
	 'file1' => 3,
	 'file3' => 1,
	 'file100' => 100,
	 'file10' => 100,
	 'file11' => 300,
	 'file9' => 301
);

ksort($name_s, SORT_NUMERIC);
print_r($name_s);
?>

Output

Array
(
    [file11] => 300
    [file9] => 301
    [file10] => 100
    [file100] => 100
    [file3] => 1
    [file1] => 3
)

Related Links


Navigation
Web
SQL
MISC
References