Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • PHP functions for applying user defined functions on array values.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 200
    Comment on it

    There are two predefined functions in PHP for applying user defined function on each element of an array.


    1. array_walk() : array_walk() applied a user function on each element of an array. It returns TRUE on success and FALSE on failure. The user function takes values and keys of supplied array as parameters.


    Syntax : array_walk(array,function,parameters)

    Description of function parameters :

    array : An array (Required)

    function : Name of user function (Required)

    parameters : Defined additional parameter for user function (Optional)


    Example :

    function printAbbreviation($value,$key,$parameter){
        echo $key.$parameter.$value."<br/>";
    }
    
    $arr = array( "Sun"=>"Sunday", "Mon"=>"Monday", "Tue"=>"Tuesday", "Fri"=>"Friday" );
    array_walk($arr, printAbbreviation," stands for ");
    

    Output :

    Sun stands for Sunday
    Mon stands for Monday
    Tue stands for Tuesday
    Fri stands for Friday
    


    2. array_map() : array_map() applied a user defined function to each value of an array and returns a new array with new values retrieved after applying user function. The number of parameters of user function should match the number of arrays passed to the array_map().


    Syntax : array_map(function,array1,array2...)

    Description of function parameters :

    function : Name of user function (or can be null) (Required)

    array1 : An array (Required)

    array2 : An array (Optional)


    Example1 :

    function square($param1){
        return $param1*$param1;
    }
    
    $numbers = array(2,5,7,10);
    $result_array = array_map(square,$numbers);
    print_r($result_array);
    

    Output :

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

    Example 2 :

    function checkMonth($par1,$par2)
    {
         if($par1===$par2)
           {
               return "same";
            }
        return "different";
    }
    
    $arr1 = array("Jan","Feb","May","Nov");
    $arr2 = array("Jan","June","May","Dec");
    $result = array_map("checkMonth",$arr1,$arr2)
    print_r($result);
    

    Output :

    Array
    (
        [0] => same
        [1] => different
        [2] => same
        [3] => different
    )
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: