Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Apply a user function on each element of an array

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 370
    Comment on it

    This article demonstrates some predefined functions of PHP which are used to apply a user defined function on each element of an array. The list and details of each function are given below :

     

    1. array_map()

    array_map() function applies a user function to each element of the first array and returns an array with new values after applying the callback function on each element.

     

    syntax : array_map(user_function, array1, array2...)

    user_function : Specifies a user function to apply on each element of an array.(Required)

    array1 : Specifies an array.(Required)

    array2 : Specifies another array.(Optional)

     

    Description : array_map() function accepts a user defined function and one or more array as arguments. The function apply the user function to each element of the first array and returns an array with elements after applying the user function. The number of arguments in user function should be equal to number of arrays passed as arguments to array_map() function.

     

    Result : The function returns an array containing elements from array1 after applying a user function to each element.

     

    Example1 :

    <?php
    function twice($v)
    {
        return($v * 2);
    }
    
    $arr = array(1, 2, 3, 4, 5);
    $result = array_map("twice", $arr);
    print_r($result);
    ?>

    Output : Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )

     

    Example 2 : Using more arrays

    <?php
    function show($a, $b){
      return ("Square of $a is $b");
    }
    
    $arr1 = array(1, 2, 3, 4);
    $arr2 = array(1, 4, 9, 16);
    
    $final = array_map("show", $arr1, $arr2);
    echo "<pre>";
    print_r($final);
    echo "</pre>";
    ?>

    Output :

    Array
    (
        [0] => Square of 1 is 1
        [1] => Square of 2 is 4
        [2] => Square of 3 is 9
        [3] => Square of 4 is 16
    )

     

    Note : When using two or more arrays as arguments, the length of arrays should be equal because the callback function applied parallel to array elements. So in result array, a shorter array will be extended with empty elements to match with the length of longest array.

     

    Example 3 : Creating array of arrays

    <?php
    $arr1 = array(1, 2, 3, 4);
    $arr2 = array("One", "Two", "Three", "Four");
    $final = array_map(null,$arr1,$arr2);
    echo "<pre>";
    print_r($final);
    echo "</pre>";
    ?>

    Output :

    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => One
            )
        [1] => Array
            (
                [0] => 2
                [1] => Two
            )
        [2] => Array
            (
                [0] => 3
                [1] => Three
            )
        [3] => Array
            (
                [0] => 4
                [1] => Four
            )
    )

     

     

    2. array_walk()

    array_walk() function used to applying a user defined function to all elements of an array.

     

    syntax : array_walk(array, user_function, user_data) 

    array : Specifies an array.(Required)

    user_function : Specifies a user function to apply on array elements.(Required)

    user_data : Specifies an additional(third) parameter to the user-defined function.(Optional)

     

    Description : array_walk() applies a callback function on each element of an array. The array_walk() will apply a callback function to every element without affecting by array pointer position.  The array keys and values are parameters of callback function, array values used as first parameter and keys used as second parameter. If the optional additional parameter is supplied, it used as third parameter for the callback function. You can pass any number of additional parameters.

     

    Result : The function returns TRUE on success and False on failure.

     

    Note :

    1. To change the values of array elements using a user function to specify the first parameter as a reference for example &value. Then the changes made to this value also apply on original array.

    2. If a user defined function requires more parameters than supplied, the function generates an E_WARNING on each function call.

     

    Example1 :

    <?php
    function display($val,$key)
    {
    echo "arr[$key] => $val";
    echo "<br>";
    }
    $arr=array("1"=>"red","2"=>"yellow","3"=>"green","4"=>"blue");
    array_walk($arr,"display");
    ?>

    Output :

    arr[1] => red
    arr[2] => yellow
    arr[3] => green
    arr[4] => blue

     

    Example 2 : With additional parameter

    <?php
    function display($val,$key,$str)
    {
    echo "index ".$key.$str.$val;
    echo "<br>";
    }
    $arr=array("1"=>"red","2"=>"yellow","3"=>"green","4"=>"blue");
    array_walk($arr,"display"," has value ");
    ?>

    Output :

    index 1 has value red
    index 2 has value yellow
    index 3 has value green
    index 4 has value blue

     

    Example 3 : Using reference

    <?php
    function change_color(&$val,$key)
    {
    $val="pink";
    }
    $arr=array("1"=>"red","2"=>"yellow","3"=>"green","4"=>"blue");
    array_walk($arr,"change_color");
    print_r($arr);
    ?>

    Output : Array ( [1] => pink [2] => pink [3] => pink [4] => pink )

     

     

    3. array_walk_recursive()

    array_walk_recursive() is also applies a user defined function to each array element just like array_walk(). The only difference between both functions is array_walk_recursive() applies a callback function to elements of  the inner arrays also.

     

    syntax : array_walk_recursive(array, user_function, user_data)

    array : Specifies an array.(Required)

    user_function : Specifies a user function to apply on array elements.(Required)

    user_data : Specifies an additional(third) parameter to the user-defined function.(Optional)

     

    Description : This function applies a callback function on each element of an array. The function also applies callback function on inner array elements. Generally callback function takes two parameters, input array values used as first parameter and keys used as second parameter. If the optional additional parameter is supplied, it used as third parameter for the callback function. You can pass any number of additional parameters. To change the values of elements using a callback function, specify the first parameter as a reference.

     

    Result : This function returns TRUE on success and FALSE on failure.

     

    Example :

    <?php
    function show($value,$index){
    	echo "The value at index $index is $value";
    	echo "<br>";
    }
    
    $arr1=array("1"=>".NET","2"=>"JAVA","3"=>"Python");
    $arr2=array($arr1,"a"=>"Android","b"=>"IOS");
    array_walk_recursive($arr2,"show");
    ?>

    Output :

    The value at index 1 is .NET
    The value at index 2 is JAVA
    The value at index 3 is Python
    The value at index a is Android
    The value at index b is IOS

     

 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: