Like in any other programming language PHP can work with arrays.
PHP Arrays can be two, tree or more dimensional.
PHP Arrays can contain strings, integers, arrays, etc.
When we fill an array with data this data can be some random data. Later, when we want to display this data, we want to get sorted and structured result. We can this with
PHP Array Sort functions.
In this tutorial I will show you the main sort unctuion:
sort(), asort(), ksort(), natsort() and their derivatives.
<?php
$cars=array('Ford', 'Chevrolet', 'Mercedes', 'Chrysler', 'Dodge');
sort($cars);
foreach ($cars as $key => $value) {
echo "cars[".$key."]=".$value."\n";
}
?>
The above example will display:
cars[0]=Chevrolet
cars[1]=Chrysler
cars[2]=Dodge
cars[3]=Ford
cars[4]=Mercedes
======================================================================
<?php
$cars=array('Ford', 'Chevrolet', 'Mercedes', 'Chrysler', 'Dodge');
asort($cars);
foreach ($cars as $key => $value) {
echo "cars[".$key."]=".$value."\n";
}
?>
The above example will display:
cars[1]=Chevrolet
cars[3]=Chrysler
cars[4]=Dodge
cars[0]=Ford
cars[2]=Mercedes
<?php
$cars=array('x'=>'Ford', 'r'=>'Chevrolet', 'a'=>'Mercedes', 'w'=>'Chrysler', 'f'=>'Dodge');
ksort($cars);
foreach ($cars as $key => $value) {
echo "cars[".$key."]=".$value."\n";
}
?>
The above example will display:
cars[a]=Mercedes
cars[f]=Dodge
cars[r]=Chevrolet
cars[w]=Chrysler
cars[x]=Ford
======================================================================
<?php
$cars=array('x'=>'Ford', 'r'=>'Chevrolet', 'a'=>'Mercedes', 'w'=>'Chrysler', 'f'=>'Dodge');
krsort($cars);
foreach ($cars as $key => $value) {
echo "cars[".$key."]=".$value."\n";
}
?>
The above example will display:
cars[x]=Ford
cars[w]=Chrysler
cars[r]=Chevrolet
cars[f]=Dodge
cars[a]=Mercedes
posted on 2009-Jun-16 | 01:43:19 AM
Thank you :)