PHP: Make an Alphabetical Selection from Elements of an Array
Posted on October 5, 2008, Filled under PHP,
Bookmark it
Here’s a snippet that extracts elements from an array starting with a specific letter (alphabetical search).
$programming_languages = array('A+', 'A++', 'A# .NET', 'A# (Axiom)', 'A-0', 'B', 'Baja', 'BeanShell', 'C#', 'Cayenne', 'JavaScript', 'Java', 'JScript', 'Python', 'Perl', 'PHP', 'Visual Basic .NET', 'Visual FoxPro', 'ZOPL', 'ZPL');
function alpha_search($array, $letter = 'a') // 'a' is the default value
{
return array_filter($array, create_function('$var', 'return (strtolower(trim($var{0})) == strtolower("'.$letter.'"));'));
}
/* Values starting with 'A' */
echo '<pre>'; print_r(alpha_search($programming_languages, 'a')); echo '</pre>';
/* Values starting with 'V' */
echo '<pre>'; print_r(alpha_search($programming_languages, 'v')); echo '</pre>';NOTE: In the second argument you can use either a lower case letter or an upper case letter. It’s case insensitive.
Here’s how our sample ouput will look like:
Array
(
[0] => A+
[1] => A++
[2] => A# .NET
[3] => A# (Axiom)
[4] => A-0
)
Array
(
[16] => Visual Basic .NET
[17] => Visual FoxPro
)Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- October 5, 2008
- article by Gabriel C.
- Leave a reply!
Related Posts
How to make an alphabetical searchat August 30, 2008
PHP: Usage of Range() Function (Alphabetical & Numerical Output)at September 2, 2008
PHP: How to remove empty values from an arrayat May 21, 2008 with 7 comments
Display Values from an Array in Random Orderat October 2, 2008
PHP: How to select a random value from an array using a specified rangeat September 20, 2008
