Search code examples
phparraysstringstring-comparisonstrcmp

PHP string comparison with special letters


I have an array of attributes which taken from woocommerce store using rest api. It looks like:

Array
 (
 [0] => stdClass Object
    (
        [id] => 6
        [name] => Modelis
        [position] => 0
        [visible] => 1
        [variation] => 1
    )

[1] => stdClass Object
    (
        [id] => 5
        [name] => Krāsa
        [position] => 1
        [visible] => 1
        [variation] => 1
    )

)

In this array I want to find item with name 'Krāsa'. As it contains special letters 'ā', simple comparison doesnt work:

foreach ($attributes as $item):
  if (!strcmp($item->name, 'Krāsa')):
    print_r('Names match');
  endif;
endforeach;

Such if clause is always false although there is name Krāsa in the array. Maybe that's my poor background, but I would like to know, how to properly compare such strings?

Many thanks.


Solution

  • In some cases, when you're having trouble with the encoding of your strings, you can convert your strings encoding.

    foreach ($attributes as $item):
        if (strcmp(mb_convert_encoding($item->name, 'utf-8', 'auto'), mb_convert_encoding('Krāsa', 'utf-8', 'auto')) == 0):
            print_r('Names match');
          endif;
        endforeach;