I am going through some PHP array exercises on w3resource because I want to get to grips with all the different functions PHP offers for arrays. I have just done this one:
- Write a PHP script to sort the following associative array :
array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40")
ina) ascending order sort by value
b) ascending order sort by Key
c) descending order sorting by Value
d) descending order sorting by Key
And here is my code:
<?php
echo "<pre>";
$people = array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");
function display($array)
{
foreach($array as $p => $a)
{
echo "$p\t $a<br>";
}
}
//sorted by value, ascending
asort($people);
display($people);
echo"<br>";
//sorted by key, ascending
ksort($people);
display($people);
echo"<br>";
//sorted by value, descending
arsort($people);
display($people);
echo"<br>";
//sorted by key, descending
krsort($people);
display($people);
echo "</pre>";
?>
I was pretty content with how I solved this, using the display()
helper method to cut down on typing.
However, the example on the website is as follows:
<?php
echo "
Associative array : Ascending order sort by value
";
$array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); asort($array2);
foreach($array2 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Ascending order sort by Key
";
$array3=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); ksort($array3);
foreach($array3 as $y=>$y_value)
{
echo
"Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Descending order sorting by Value
";
$age=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");
arsort($age);
foreach($age as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Descending order sorting by Key
";
$array4=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); krsort($array4);
foreach($array4 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
?>
This came across, to me, as flawed code in some ways, because I wondered why the same array was declared multiple times when it seems unnecessary.
Am I missing something with this example code? Is there a reason I should not use a
display()
helper method?Is readability improved by following
echo
immediately with a line, as is done in the example?Is it good practise to use the
.
concatenation operator alongside'
'
(single quotation marks), as opposed to simply putting everything inside"
"
(doubles)? (I find the latter more readable and easier to work with.)Is it acceptable to place more than one statement per line, as is done in the example
$array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); asort($array2);