Open In App

PHP | ArrayIterator ksort() Function

Last Updated : 21 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The ArrayIterator::ksort() function is an inbuilt function in PHP which is used to sort the array element by key.

Syntax:

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:

s k e e G f r o

Program 2:




<?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:

key: a  Value: Geeks
key: b  Value: Geeks
key: c  Value: for
key: 0  Value: Computer
key: 1  Value: Science
key: 2  Value: Portal

Reference: https://www.php.net/manual/en/arrayiterator.ksort.php



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads