04
Jun
PHP Arrays Ex. #2: Simple Array Loop
In this post, I will go over question number #2 from http://phpexercises.com/php-simple-array-loop-exercise.html
Please look at my code (what I came up with):
<?php
/*
PHP Arrays Ex. #2: Simple Array Loop
For this exercise, you will use a list of ten of the largest cities in the world.
(Please note, these are not the ten largest, just a selection of ten from the largest cities.)
Create an array with the following values: Tokyo, Mexico City, New York City, Mumbai, Seoul,
Shanghai, Lagos, Buenos Aires, Cairo, London.
Print these values to the browser separated by commas, using a loop to iterate over the array.
Sort the array, then print the values to the browser in an unordered list, again using a loop.
Add the following cities to the array: Los Angeles, Calcutta, Osaka, Beijing. Sort the array
again, and print it once more to the browser in an unordered list.
*/
$list = array(‘Tokyo’ , ‘Mexico City’, ‘New York City’, ‘Mumbai’, ‘Seoul’, ‘Shanghai’, ‘Lagos’, ‘Buenos Aires’, ‘Cairo’, ‘London’);
asort($list);
foreach($list as $key => $value) {
echo $value;
echo ‘, ‘;
}
array_push($list, ‘Los Angeles’, ‘Calcutta’, ‘Osaka’, ‘Beijing’);
echo ‘<br /><br />’;
asort($list);
foreach($list as $key => $value) {
echo $value;
echo ‘, ‘;
}
?>
Now look at their code answer (click on view script):
http://phpexercises.com/php-simple-array-loop-exercise.html
The difference between our codes lies in the function to sort the array. I used asort while they used sort. We both got the same results using different functions. What is the difference though? Let’s check it out. When using sort, new keys are assigned for the elements in the array. For example, if you have ([a] => ‘me’, [b] => ‘you’) it sorts to ([0] => ‘me’, [1] => ‘you’). With asort, the function sorts an array by values. The values keep their original key(index).