PHP Function: Array ksort()

In this article, we will discuss the ksort() function in PHP. The ksort() function is used to sort an array by key in ascending order. We will go through the syntax, parameters, and return value of this function, and provide some examples to help you understand it better. Let's dive into it.

Syntax

ksort($array, $sorting_type);

Parameters

The ksort() function takes two parameters:

  • $array: Required. Specifies the array to be sorted.
  • $sorting_type: Optional. Specifies the sorting type, which can be one of the following two constants: SORT_REGULAR (default) and SORT_NUMERIC.

Return Value

The ksort() function returns a boolean value, true on success, and false on failure.

Example 1: Sorting an Associative Array by Key

<?php

$age = ["Peter" => "35", "Ben" => "37", "Joe" => "43"];
ksort($age);

print_r($age);

Output:

Array
(
    [Ben] => 37
    [Joe] => 43
    [Peter] => 35
)

Example 2: Sorting an Associative Array by Key in Reverse Order

<?php

$age = ["Peter" => "35", "Ben" => "37", "Joe" => "43"];
krsort($age);

print_r($age);

Output:

Array
(
    [Peter] => 35
    [Joe] => 43
    [Ben] => 37
)

Example 3: Sorting an Indexed Array by Key

<?php

$colors = ["red", "green", "blue", "yellow"];
ksort($colors);

print_r($colors);

Output:

Array
(
    [0] => blue
    [1] => green
    [2] => red
    [3] => yellow
)

Example 4: Sorting an Indexed Array by Key in Reverse Order

<?php

$colors = array("red", "green", "blue", "yellow");
krsort($colors);

print_r($colors);

Output:

Array
(
    [3] => yellow
    [2] => red
    [1] => green
    [0] => blue
)

Conclusion

In this article, we have discussed the ksort() function in PHP, which is used to sort an array by key in ascending order. We have gone through its syntax, parameters, and return value, and provided some examples to help you understand it better. We hope this article has been useful to you. If you have any questions or suggestions, please feel free to leave a comment below.

			graph TD
    A[PHP array] -->|ksort| B[Sorted PHP array]
		

Practice Your Knowledge

What is the purpose of the ksort() function in PHP?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?