<?php
$array = array(
"1" => 'Hi',
"4" => 'are',
"3" => 'How',
"7" => 'my',
"6" => 'you',
"9" => 'brother',
);
forEach($array as $key => $value) {
echo $key;
echo ':-';
print_r($value);
echo '<br/>';
}
?>
the out put of this code is
1:-Hi
4:-are
3:-How
7:-my
6:-you
9:-brother
but i need to display this order by key. please tell me which is easiest way
thanks
Use ksort
ksort($array);
foreach($array as $key => $value) {
echo $key;
echo ':-';
print_r($value);
echo '<br/>';
}
The nice thing about PHP is that there's a function for everything. You can use the ksort
function to sort the array by its keys: http://php.net/manual/en/function.ksort.php
Your new code would look like this:
<?php
$array = array(
"1" => 'Hi',
"4" => 'are',
"3" => 'How',
"7" => 'my',
"6" => 'you',
"9" => 'brother',
);
ksort($array);
forEach($array as $key => $value) {
echo $key;
echo ':-';
print_r($value);
echo '<br/>';
}
?>
use ksort()
, this will arrange it by key order.
<?php
$array = array(
"1" => 'Hi',
"4" => 'are',
"3" => 'How',
"7" => 'my',
"6" => 'you',
"9" => 'brother',
);
ksort($array);
forEach($array as $key => $value) {
echo $key;
echo ':-';
print_r($value);
echo '<br/>';
}
?>