2

i have a problem with insensitive array_keys and in_array ... I developing a translator, and i have something like this:

$wordsExample = array("example1","example2","example3","August","example4");
$translateExample = array("ejemplo1","ejemplo2","ejemplo3","Agosto","ejemplo4");


function foo($string,$strict=FALSE)
{
    $key = array_keys($wordsExample,$string,$strict);
    if(!empty($key))
      return $translateExample[$key[0]];
    return false;
}

echo foo('example1'); // works, prints "ejemplo1"
echo foo('august');  // doesnt works, prints FALSE

I tested with in_array and same result...:

function foo($string,$strict=FALSE)
{
    if(in_array($string,$wordsExample,$strict))
      return "WOHOOOOO";
    return false;
}

echo foo('example1'); //works , prints "WOHOOOOO"
echo foo('august'); //doesnt works, prints FALSE
hakre
  • 193,403
  • 52
  • 435
  • 836
Stefan Luv
  • 1,179
  • 3
  • 12
  • 28

2 Answers2

1

Create the array and find the keys with with strtolower:

$wordsExample = array("example1","example2","example3","August","example4");
$lowercaseWordsExample = array();
foreach ($wordsExample as $val) {
    $lowercaseWordsExample[] = strtolower($val);
}

if(in_array(strtolower('august'),$lowercaseWordsExample,FALSE))
      return "WOHOOOOO";

if(in_array(strtolower('aUguSt'),$lowercaseWordsExample,FALSE))
      return "WOHOOOOO";

Another way would be to write a new in_array function that would be case insensitive:

function in_arrayi($needle, $haystack) {
    return in_array(strtolower($needle), array_map('strtolower', $haystack));
}

If you want it to use less memory, better create the words array using lowercase letter.

Kuf
  • 17,318
  • 6
  • 67
  • 91
  • Yes, is one way to do it, but system can be use many memory if you have many translations to do – Stefan Luv Aug 21 '12 at 06:40
  • You don't need to create two arrays, create just the one but create it using lowercase letter. That way you won't have to create another instance – Kuf Aug 21 '12 at 06:44
  • consider using array_map() to lowercase the array entries – Mark Baker Aug 21 '12 at 06:46
0

I created a small function a while to get, to test clean-URLs as they could be uppercase, lowercase or mixed:

function in_arrayi($needle, array $haystack) {

    return in_array(strtolower($needle), array_map('strtolower', $haystack));

}

Pretty easy this way.

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126