Make an alphabetical selection from elements of an array

Save to StumbleUpon Stumble Upon it!   Save to Del.icio.us Save to Del.icio.us

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
)
 The archive is made using WinZip 12.0. If you're having problems unzipping it, consider using WinRar, WinAce or a similar software to extract the files from the archive.

Be notified when we have new posts by subscribing to  RSS BitRepository RSS Feed.
   Save to StumbleUpon   

Similar entries

Comment on this post!

Subscribe to BitRepository RSS Feed
[Advertise with us]