anon
anon

Reputation:

Applying a function for each value of an array

Considering an array of strings:

$array = ('hello', 'hello1', 'hello2');

I need to preg_quote($value,'/'); each of the values.

I want to avoid using foreach. Array walk doesn't work because it passes the key too.

array_walk($array,'preg_quote','/'); //> Errors, third parameter given to preg_quote

Any alternative?

Upvotes: 6

Views: 9558

Answers (5)

dynamic
dynamic

Reputation: 48131

The alternative we forgot to mention is:

function user_preg_quote($key, $value) {
   return preg_quote($value, '/');
}

array_walk($array, 'user_preg_quote'); 

But still a simple foreach would be better maybe.

Upvotes: 0

Ernestas Stankevičius
Ernestas Stankevičius

Reputation: 2493

Use foreach. It's made for that reason. But if you insist:

array_walk($arr, create_function('&$val', '$val = preg_quote($val, "/");'));

Upvotes: 1

genesis
genesis

Reputation: 50976

Try array_map() [doc] with an anonymous function (>= 5.3):

$array = array_map(function($value){
    return preg_quote($value, '/');
}, $array);

Working demo

Upvotes: 24

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28005

You can do (with PHP 5.3):

array_map(function($elem) { return preg_quote($elem, '/'); }, $array);

In PHP <5.2 there are no annoymous functions (first argument of array map) and in that case you should make a global function.

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270647

Use array_map()

$newarray = array_map(function($a) {return preg_quote($a, '/');}, $input_array);

Upvotes: 3

Related Questions