Saturday, July 4th, 2009

Make an alphabetical selection from elements of an array

by Gabriel on 05/10/08 at 5:45 am

Save to StumbleUpon Stumble Upon it!     Save to Del.icio.us Save to Del.icio.us    Share on Twitter! Share on Twitter!

Greetings! Subscribe to my RSS feed or get my latest post directly in your mailbox. Thanks for visiting!

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
)
Be notified when we have new posts by subscribing to BitRepository RSS Feed.
Support us!Did you like this post?
Please spread the word!
Save to StumbleUpon  Save to Del.icio.us  Share on Twitter!    

Leave a Comment