user2613707
user2613707

Reputation: 79

Array_map versus array walk because of warning issues

Hi i have a simple question I am using array_walk to encode an array to utf8 like this :

  array_walk($row, 'utf8_encode'); 

but i keep on getting a php warning this one

   (PHP Warning:  Wrong parameter count for utf8_encode() ).

So i was wondering does using array_map instead to encode to utf8 (array_walk('utf8_encode',$row);) have the same effect, because with array map i don't have the warning issue.

Thanks.

Upvotes: 0

Views: 1622

Answers (4)

user4035
user4035

Reputation: 23729

Definitely, array_map is better for you. Because you want to encode only the values of your row. array_walk requires the callback function to accept 2 parameters: value and key.

As you are not going to encode the key, it will be more efficient to use array_map.

http://php.net/manual/en/function.array-walk.php

http://www.php.net/manual/en/function.array-map.php

Upvotes: 1

deceze
deceze

Reputation: 522085

array_walk passes two parameters to the callback: the value and the key. utf8_encode expects one parameter and hence complains. array_map will work better here since it doesn't pass additional parameters to the callback:

$row = array_map('utf8_encode', $row);

Having said that, in 99% of all cases utf8_encode is the wrong thing to use. Read What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text and UTF-8 all the way through.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

That's because, utf8_encode expects only 1 param, but array_walk() gives 2. You can do it like:

function encode_items(&$item, $key) {
    $item = utf8_encode($item);
}
array_walk($row, 'encode_items');

or supress warning (not good)

@array_walk($row, 'utf8_encode');

or better use array_map():

function utf8_encode_array($array) {
    return array_map('utf8_encode', $array);
}
$encoded = array_map('utf8_encode_array', $row);

Upvotes: 1

cske
cske

Reputation: 2243

utf8_encode has a single parameter, fix:

array_walk($row, function (&$value,$key) {
    return utf8_encode($value);
}); 

Upvotes: 0

Related Questions