views:

232

answers:

4

I'm trying to write a few lines of code to make a case insensitive array unique type function. Here's what I have so far:

foreach ($topics as $value) {
    $lvalue = strtolower($value);
    $uvalue = strtolower($value);

    if (in_array($value, $topics) == FALSE || in_array($lvalue, $topics) == FALSE || in_array($uvalue, $topics) == FALSE) {
        array_push($utopics, $value);
    }
}

The trouble is the if statement. I think there's something wrong with my syntax, but I'm relatively new to PHP and I'm not sure what it is. Any help?

+1  A: 

You're setting both lvalue and uvalue to the lower case version.

 $uvalue = strtolower($value);

should be

 $uvalue = strtoupper($value);

That said, this might be a little faster. The performance of your function will degrade exponentially, while this will be more or less linear (at a guess, not a comp-sci major...)

<?php

function array_iunique($ar) {
  $uniq = array();
  foreach ($ar as $value)
    $uniq[strtolower($value)] = $value;
  return array_values($uniq);
}
?>
meagar
wow -.- sometimes I guess I just need another pair of eyes. haha thanks! That still doesn't quite do it, though. Not sure what's wrong...The values that are showing up are values that are duplicates (like jQuery and jQuery) both are displaying. But with values that are different (like php and PHP) neither is showing up. Weird...
WillyG
Nice solution! Only thing that bothers me is that the original `array_unique` function preserves the keys whereas this does not but I guess it doesn't matter in this case.
Tatu Ulmanen
@Tatu it'd be hard to preserve the keys when you're discarding some of the data... which key do you preserve? The first, or the last, or one chosen at random?
meagar
@meagar, as the manual states: "Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys."
Tatu Ulmanen
A: 

Should $uvalue not be uppercase? So

$uvalue = strtoupper($value):
Bright010957
+4  A: 
function array_iunique($array) {
return array_intersect_key($array,array_unique(
                array_map(strtolower,$array)));
}
Pentium10
Awesome! Thanks!
WillyG
A: 

and another alternative...

function array_iunique($topics) {

    $ltopics = array_map('strtolower', $topics);
    $cleanedTopics = array_unique($ltopics);

    foreach($topics as $key => $value) {
        if(!isset($cleanedTopics[$key])) {
            unset($topics[$key]);
        }
    }

    return $topics;

}

Pentium10's is better though.

Drew G