2013-02-21

The array_map() problems!~..

Some time ago, I had a huge problem with understanding the array_map () function. Jeffrey Way defines it as a PHP function, which is built from 2 parameters. The first is the function to execute, and the second parameter is the array, are you working with. First parameter, within array_map, executes on every item in our parameter 2, in the array. So, array_map() syntax looks like:

        array_map(function() {
                    }, array1,array2,array3,...) // required is only array1, the remaining arrays are optional

He also gave me some example of use:

     
       function array_pluck($toPluck, $arr) {
                  $ret= array_map(function($item) use ($toPluck){
                  return $item[$toPluck];
                  }, $arr);
       print_r($ret);
       }
      ?>

But, as on my first contact with this function, the example was too much complicated for me. Or maybe I could understand it just because of 'use' enclosure, which can not be used in older versions of PHP. But whether to this, I asked my boyfriend to help me, and after his lesson, I finally understood, how array_map() working. There is his example:

      
       $table = [1,2,3] // so we have an array called $table
       $new_table = array_map(function($item) { // we create a new array, equal to array_map
             return $item+1;
             }, $table); // The function within array_map(), is working on every item from the $table and for each item, adds one
       print_r($new table); //now let's print it and see the result
       ?>



RESULT:

Array(
                  [0] => 2
                  [1] => 3
                   [2] => 4)

So, as you can see, the array_map() function works on array which as components, contains other arrays with other elements. Array_map() applying to array, execute function to each one and after that, returns an array containing all this elements, that are the execute function result.

Of course, if you want to see the result of array_map(), you don't have to use print_r, which gives you a lot of, unnecessary details. You can see the result, by using nicer way, namely, using 'foreach' conditional statement:

      

        $t = ['mama', 't', 'xx'];
        $r = array_map(function($i){
               return strlen($i);
               },$t);
        foreach($r as $item) {
               echo $item.' ';
        }
        ?>

RESULT:   4 1 2

Brak komentarzy:

Prześlij komentarz

Dziękuję Ci za poświęcony czas i pozostawienie komentarza :)