PHP | ArrayIterator ksort() Function
Last Updated :
21 Nov, 2019
Improve
The ArrayIterator::ksort() function is an inbuilt function in PHP which is used to sort the array element by key.
Syntax:
php
php
void ArrayIterator::ksort( void )Parameters: This function does not accept any parameters. Return Value: This function does not return any value. Below programs illustrate the ArrayIterator::ksort() function in PHP: Program 1:
<?php
// Declare an ArrayIterator
$arrItr = new ArrayIterator(
array(
5 => 'G',
4 => 'e',
3 => 'e',
2 => 'k',
1 => 's',
6 => 'f',
8 => 'o',
7 => 'r'
)
);
// Sort the array element by key
$arrItr->ksort();
// Display the element
while($arrItr->valid()) {
echo $arrItr->current() . " ";
$arrItr->next();
}
?>
Output:
Program 2:
s k e e G f r o
<?php
// Declare an ArrayIterator
$arrItr = new ArrayIterator(
array(
"a" => "Geeks",
"c" => "for",
"b" => "Geeks"
)
);
// Append the element into array
$arrItr->append("Computer");
$arrItr->append("Science");
$arrItr->append("Portal");
// Sort the array element by key
$arrItr->ksort();
// Display the result
foreach($arrItr as $element) {
echo "key: " . $arrItr->key() . " Value: "
. $arrItr->current() . "\n";
}
?>
Output:
Reference: https://www.php.net/manual/en/arrayiterator.ksort.php
key: a Value: Geeks key: b Value: Geeks key: c Value: for key: 0 Value: Computer key: 1 Value: Science key: 2 Value: Portal