0

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.

Kieran
  • 2,200
  • 1
  • 15
  • 17

4 Answers4

1

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);
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
1

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

user4035
  • 22,508
  • 11
  • 59
  • 94
0

utf8_encode has a single parameter, fix:

array_walk($row, function (&$value,$key) {
    return utf8_encode($value);
}); 
cske
  • 2,233
  • 4
  • 26
  • 24
0

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.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889