pTutorial

New way to learn PHP

PHP 5 Sorting of an Array Part 2

ksort() function

The ksort() function sorts an array according to its key in ascending order.

Example of array sorting in ascending alphabetical order

<?php

$name=array(
"Bmw"=>" BMW Z4 M Coupe",
"Audi"=>"R8",
"SKODA"=>"Fabia"
);

ksort($name);

echo "Key"."--------". "Value
"; foreach($name as $key=>$key_value) { echo $key ."--------". $key_value; echo "
"; } ?>

krsort() function

The krsort() function sorts an array according to its key values in descending order.

Example of array sorting in ascending alphabetical order

<?php

$name=array(
"Bmw"=>" BMW Z4 M Coupe",
"Audi"=>"R8",
"SKODA"=>"Fabia"
);

krsort($name);

echo "Key"."--------". "Value
"; foreach($name as $key=>$key_value) { echo $key ."--------". $key_value; echo "
"; } ?>

array_multisort()

array_multisort() function sort multiple array at a time and also sort the multi-dimensional array. By passing all three arrays to array_multisort().

Example of array_multisort()

<?php

$numbers=array(40,5,20,12,101);
$numbers1=array(40,5,20,12,101);

array_multisort($numbers,$numbers1);
echo "First array"."
"; $arrlength=count($numbers); for($x=0;$x<$arrlength;$x++) { echo $numbers[$x]; echo "
"; } echo "Second array"."
"; print_r($numbers1); ?>

Note: array_multisort function accept only same size array, that means you can sort same size numeric and Associative array.

Example of array_multisort()

<?php

$cities = array( "Mumbai", "Delhi", "Agra", "Raebareli" );

$number = array( 500, 700, 152, 900 );

array_multisort( $cities, $number );

print_r ( $cities );

echo " 
"; print_r ( $number ); ?>

shuffle() function

The function shuffle () sorts the elements of an array in random order. Shuffle function used both in index and associative array.

Example of an array shuffle function

<?php

$cars = array ("Alto", "swift", "Skoda", "audi", "ferrari");

echo "before sorting
" ; Print_r($cars); shuffle($cars); echo "
After sorting
"; Print_r($cars); ?>

Example of an array shuffle function (numerical)

<?php

$numbers=array(40,5,20,12,101);

shuffle($numbers);

$arrlength=count($numbers);

for($x=0;$x < $arrlength;$x++)
   {
   echo $numbers[$x];

   echo "
"; } ?>

QUOTES OF THE DAY

Knowledge without integrity is dangerous and dreadful.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER