PHP/Data Structure/array filter

Материал из Web эксперт
Версия от 07:02, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Array filter

 
<?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 "<p>Original:</p>";
  array_display($arr, TRUE);
  print "<p>Filtered:</p>";
  array_display($copy, TRUE);
  print "<p>Filtered and re-indexed:</p>";
  array_display($reindexed, TRUE);
?>



array_filter demo

 
<?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 "<p>Filtered:</p>"; 
array_display($copy, TRUE); 
print "<p>Filtered and reindexed:</p>"; 
array_display($reindexed, TRUE); 
?>



array_filter( ) filters elements through a function

 
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);
?>



Filtering Arrays Using array_filter()

 
<?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); 
?>



Using the array_filter() Function

 
<?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);
?>