PHP/Data Structure/array filter
Содержание
Array filter
<source lang="html4strict">
<?php
function array_display($array, $pre=FALSE) { $tag = $pre ? "pre" : "p"; printf("<%s>%s</%s>\n", $tag, var_export($array, TRUE), $tag); } $arr = array(2, "two", 0, "NULL", NULL, "FALSE", FALSE, "empty", ""); $copy = array_filter($arr); $reindexed = array_values($copy);print "
Original:
";array_display($arr, TRUE);print "
Filtered:
";array_display($copy, TRUE);print "
Filtered and re-indexed:
";array_display($reindexed, TRUE);
?>
</source>
array_filter demo
<source lang="html4strict">
<?php function array_display($array, $pre=FALSE) {
$tag = $pre ? "pre" : "p"; printf("<%s>%s</%s>\n", $tag, var_export($array, TRUE), $tag);
} $arr = array(2, "two", 0, "NULL", NULL, "FALSE", FALSE, "empty", ""); $copy = array_filter($arr); $reindexed = array_values($copy);
array_display($arr, TRUE);
print "Filtered:
";array_display($copy, TRUE);
print "Filtered and reindexed:
";array_display($reindexed, TRUE); ?>
</source>
array_filter( ) filters elements through a function
<source lang="html4strict">
array array_filter ( array arr [, function callback] ) <?
function endswithy($value) { return (substr($value, -1) == "y"); } $people = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Joe"); $withy = array_filter($people, "endswithy"); var_dump($withy);
?>
</source>
Filtering Arrays Using array_filter()
<source lang="html4strict">
<?php function array_display($array, $pre=FALSE) {
$tag = $pre ? "pre" : "p"; printf("<%s>%s</%s>\n", $tag, var_export($array, TRUE), $tag);
} function is_romance($lang) {
return in_array($lang, array("French", "Spanish", "Portuguese", "Italian"));
}
$countries = array( "USA" => "English", "Spain" => "Spanish", "Brazil" => "Portuguese"); $rom_countries = array_filter($countries, "is_romance"); array_display($rom_countries, TRUE); ?>
</source>
Using the array_filter() Function
<source lang="html4strict">
<?php
function filter_values($value) { if($value > 10) return true; return false; } $myints = array(123,45,2345,3,42); $filtered = array_filter($myints, "filter_values"); print_r($filtered);
?>
</source>