Share on Google+Share on Google+

PHP Sort Array

Advertisement
In this tutorial you will come to know about the php array. Sometimes we need to store data in a single entity called Array, unlike in other language in PHP, an array can store values of different datatype. In the following examples we will learn how to create array, associative array, how to sort values of an array, and how to sort the keys of an associative arrays are given.

PHP Sort Array:

Sometimes we need to store data in a single entity called Array, unlike in other language in PHP, an array can store values of different datatype.

In the following examples we will learn how to create array, associative array, how to sort values of an array, and how to sort the keys of an associative arrays are given.

Go through each example and you will come to know how to use array in PHP.

PHP Sort Array Example:

<?php

$array=array("Hello","New","World");

echo count($array);

sort($array);

for($i=0;$i<=4;$i++){

echo $array[$i]."<br/>";

}

$array=array("Hello","Hi","Hei");

sort($array);

for($i=0;$i<=4;$i++){

echo $array[$i]."<br/>";

}

$array=array("Hello"=>1,"Hi"=>2,"Hei"=>3);

asort($array);

foreach($array as $key=>$value){

echo "Key: ".$key."Value: ".$value."<br/>";

}

echo "<br/>";

$array=array("Hello"=>1,"Hi"=>2,"Hei"=>3);

ksort($array);

foreach($array as $key=>$value){

echo "Key: ".$key."Value: ".$value."<br/>";

}

?>

 

Output:

3Hello
New
World


Hei
Hello
Hi


Key: HelloValue: 1
Key: HiValue: 2
Key: HeiValue: 3

Key: HeiValue: 3
Key: HelloValue: 1
Key: HiValue: 2

Advertisements

Posted on: February 13, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.