PHP/Data Structure/array walk

Материал из Web эксперт
Перейти к: навигация, поиск

Apply a user function to every member of an array.

 
<?
$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
function test_alter (&$item1, $key, $prefix) {
    $item1 = "$prefix: $item1";
}
function test_print ($item2, $key) {
    echo "$key. $item2<br>\n";
}
array_walk ($fruits, "test_print");
reset ($fruits);
array_walk ($fruits, "test_alter", "fruit");
reset ($fruits);
array_walk ($fruits, "test_print");
?>



Applying Functions to Array Elements Using array_walk()

 
<?php
  function array_display($array, $pre=FALSE)
  {
    $tag = $pre ? "pre" : "p";
    printf("<%s>%s</%s>\n", $tag, var_export($array, TRUE), $tag);
  }
  function modify(&$element)
  {
    $element *= 1.5;
  }
  $array = array(10, -3.5, 2, 7);
  array_display($array, TRUE);
  array_walk($array, "modify");
  array_display($array, TRUE);
?>



array_walk() function applies a function to several or all elements in an array.

 
Its syntax is: int array_walk(array array, string func_name, [mixed data])

<?
//Using array_walk() to delete duplicates in an array:
    function delete_dupes($element) {
         static $last="";
         if ($element == $last)
              unset($element);
         else
              $last=$element;
    }
    
    $emails = array("b@b.ru", "c@w.ru", "b@b.ru");
    
    sort($emails);
    print_r($emails);
    echo "<br>";
    reset($emails);
    print_r($emails);
    echo "<br>";
    array_walk($emails,"delete_dupes");
    print_r($emails);
    echo "<br>";
    
?>