Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case-insensitive array_unique

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?

like image 525
williamg Avatar asked Feb 16 '10 21:02

williamg


People also ask

What is Array_unique?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);

Are arrays unique PHP?

The array_unique() is a built-in function in PHP and this function removes duplicate values from an array. If there are multiple elements in the array with same values then the first appearing element will be kept and all other occurrences of this element will be removed from the array.

How check value exist in array or not in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


2 Answers

function array_iunique( $array ) {     return array_intersect_key(         $array,         array_unique( array_map( "strtolower", $array ) )     ); } 
like image 184
Pentium10 Avatar answered Sep 22 '22 03:09

Pentium10


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); } ?> 
like image 29
meagar Avatar answered Sep 24 '22 03:09

meagar