Tuesday, December 31, 2024
Google search engine
HomeLanguagesPHP | ArrayIterator ksort() Function

PHP | ArrayIterator ksort() Function

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments