PHP array_map() function with example

PHP array_map() work

array_map() work is utilized to apply activities on each cluster values (components) in view of the given capacity, it sends each value of an exhibit to the given capacity and returns another cluster with the determined values.

Syntax:

array_map(function, array1, [array2], …); 

Here,

  • work is the name of the capacity, that will be utilized to apply activity on each value of the given cluster.
  • array1 is a cluster on which we need to play out the activity.
  • array2, … are discretionary parameters, we can determine different exhibits as well.

Example:

    Input:
    $arr = array(10, 20, 30, 40, 50);

    Function:
    function getSquare($value)
    {
        return ($value*$value);
    }

    Function call:
    array_map("getSquare", $arr);

    Output:
    Array
    (    
        [0] => 100   
        [1] => 400   
        [2] => 900   
        [3] => 1600  
        [4] => 2500  
    )

PHP code 1: Getting the squares and 3D shapes of all values:

<?php
    //functions
    function getSquare($value)
    {
        return ($value*$value);
    }
    function getCube($value)
    {
        return ($value*$value*$value);
    }
    
    //array
    $arr = array(10, 20, 30, 40, 50);
    
    //new array of squares of the array's values
    $arr_sqr = array_map("getSquare", $arr);
    //new array of squares of the array's values
    $arr_cube = array_map("getCube", $arr);    
    
    //printing
    print_r ($arr_sqr);
    print_r ($arr_cube);
?>

Output

Array
(    
    [0] => 100   
    [1] => 400   
    [2] => 900   
    [3] => 1600  
    [4] => 2500  
)    
Array
(    
    [0] => 1000  
    [1] => 8000  
    [2] => 27000 
    [3] => 64000 
    [4] => 125000
) 

PHP code 2: Finding a total of the values of two clusters:

<?php
    //function to add values of two arrays
    function addValues($value1, $value2)
    {
        return ($value1 + $value2);
    }
    
    //arrays
    $arr1 = array(10, 20, 30, 40, 50);
    $arr2 = array(100, 200, 300, 400, 500);
    
    $result = array_map("addValues", $arr1, $arr2);
    print_r ($result);
?>

Output

Array
(    
    [0] => 110
    [1] => 220
    [2] => 330
    [3] => 440
    [4] => 550
)

Leave a Comment

error: Alert: Content is protected!!