0

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
10
  • 2
    array_map. array_walk can modify array too. All functions are here - php.net/manual/en/ref.array.php Commented Nov 30, 2018 at 14:25
  • 1
    But array_map can't take $userdata @u_mulder Commented Nov 30, 2018 at 14:32
  • What's $userdata!? Commented Nov 30, 2018 at 14:34
  • 2
    I have no idea what you're talking about. What is $userdata? Instead of asking for a function that does what?, you should describe a real problem. Commented Nov 30, 2018 at 14:37
  • $userdata means parameter like array_walk(array,myfunction,parameter...) @Devon Commented Nov 30, 2018 at 14:38

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

Don't complicate things. Just use foreach to modify your array or to create a new one:

foreach ($presentable_cols as $key => $value) {
    $presentable_cols[$key] = "$key LIKE '% $request_data %'";
}

By the way, make sure to sanitize $request_data.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.