phparraysfunctionclosuresarray-walk

How to get a PHP function alike array_walk that will return an array?


Is there any built-in function existing in PHP alike array_walk() that will return an array instead of true or false?

For information, I am trying the following code but in the result of the code getting OR at the end of the string I need to remove this hence I need an alternative

$request_data = "Bablu"; //userdata 

$presentable_cols = array('id'=>'13141203051','name'=>'Bablu Ahmed','program'=>'B.Sc. in CSE', 'country'=>'Bangladesh');

function myfunction($value,$key,$request_data)
{
    echo " $key LIKE '% $request_data %' OR";
}
array_walk($presentable_cols,"myfunction", $request_data);

Result of the code:

id LIKE '% Bablu %' OR name LIKE '% Bablu %' OR program LIKE '% Bablu %' OR country LIKE '% Bablu %' OR

Solution

  • The use keyword allows you to introduce local variables into the local scope of an anonymous function. This is useful in the case where you pass the anonymous function to some other function which you have no control over.

    Can not use array_map as this does not work with keys (PHP's array_map including keys). Here is a possible solution:

    $request_data = "Bablu"; //userdata 
    
    $presentable_cols = array('id'=>'13141203051','name'=>'Bablu Ahmed','program'=>'B.Sc. in CSE', 'country'=>'Bangladesh');
    
    $my_arr = [];
    $myfunction = function($value,$key) use ($request_data,&$my_arr)
    {
        array_push($my_arr," $key LIKE '% $request_data %'");
    };
    
    array_walk($presentable_cols,$myfunction);
    
    echo implode("OR",$my_arr);