Long time, no post 🙂
Here is a small PHP tips&tricks post : we have an array full of values, let’s say a country list (in this example the list is limited, we don’t want to see 190+ values).
Array
(
[0] => Array
(
[0] => Afghanistan
[name] => Afghanistan
[1] => AF
[code] => AF
)
[1] => Array
(
[0] => Albania
[name] => Albania
[1] => AL
[code] => AL
)
[2] => Array
(
[0] => Algeria
[name] => Algeria
[1] => DZ
[code] => DZ
)
[3] => Array
(
[0] => Bangladesh
[name] => Bangladesh
[1] => BD
[code] => BD
)
[4] => Array
(
[0] => Barbados
[name] => Barbados
[1] => BB
[code] => BB
)
[5] => Array
(
[0] => Belgium
[name] => Belgium
[1] => BE
[code] => BE
)
[6] => Array
(
[0] => Brazil
[name] => Brazil
[1] => BR
[code] => BR
)
[7] => Array
(
[0] => Cape Verde
[name] => Cape Verde
[1] => CV
[code] => CV
)
[8] => Array
(
[0] => Cayman Islands
[name] => Cayman Islands
[1] => KY
[code] => KY
)
)
and we want to display like this
- Afghanistan
- Albania
- Algeria
- Bangladesh
- Barbados
- Belgium
- Brazil
- Cape Verde
- Cayman Islands
, the right and easy way to do this would be to retain in a variable the first letter of the last country and in another variable the first letter of the current country. We compare them and if they are different we just output the first letter and then the name of the current country. All this in just few and simple to understand lines, right? 😛
//try to do the A-Z list
$v = function to get your country list from a DB sorted by country name!;
$last_letter = '';
$current_letter = '';
for ($i=0;$i" . $current_letter . "
Great idea. Don’t forget to mention the prerequisite that the $v array must be sorted (It looks like you’re pulling the results from a database, so you probably achieve that using the ORDER BY clause)
Yes, indeed, it must be sorted in order to work as designed.
Thanks for the observation 😀
In your for loop you use a variable named ‘count’ as the value to test the $i counter variable, but you didn’t define the value of ‘count’. Is this an error, or does PHP reserve ‘count’ as a constant? If so, what is the value of ‘count’?
Wayne … count is a prebuild function that returns the number of elements of an array.
Hope this helps
Wow, cool tutorial, it really helped me a lot, it was precisly what i was looking for (^^)b
Thanks a lot 🙂