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.
Array
(
[0] => A+
[1] => A++
[2] => A# .NET
[3] => A# (Axiom)
[4] => A-0
)
Array
(
[16] => Visual Basic .NET
[17] => Visual FoxPro
)
No comments:
Post a Comment