Viewed   63 times

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?

 Answers

3
function array_iunique( $array ) {
    return array_intersect_key(
        $array,
        array_unique( array_map( "strtolower", $array ) )
    );
}
Monday, October 10, 2022
5

If you want to do that: just make sure the input data is in all lowercase, and use lowercase cases...

switch ("UPPER".toLowerCase()) {
case  "upper" :

....

Localization issues

Also, the ages old issue of localization strikes again, and plagues this thing too... For example, in the Turkish Locale, the uppercase counterpart of i is not I, but ?... And in return, the I is not transformed to i, but a "dotless i": ?. Don't underestimate this, it can be a deadly mistake...

Thursday, September 1, 2022
 
5

Use a function for the second argument for .replace() that returns the actual matched string with the concatenated tags.

Try it out: http://jsfiddle.net/4sGLL/

reg = new RegExp(querystr, 'gi');
       // The str parameter references the matched string
       //    --------------------------------------v
final_str = 'foo ' + result.replace(reg, function(str) {return '<b>'+str+'</b>'});
$('#' + id).html(final_str);​

JSFiddle Example with Input: https://jsfiddle.net/pawmbude/

Saturday, September 17, 2022
3

foreach works with a copy of $item, so you cannot modify your original array inside the foreach. One way to work around this is to use the & operator.

foreach($array as &$item) {
    if (is_array($item)) {
        $item['key3'] = 'val3';
    }
}

Another, more elegant way would be to use array_walk():

array_walk($array, function (&$v, $k) { 
    if (is_array($v)) {
        $v['key3'] = 'val3';
    }
});

This example will work from PHP 5.3, where Closures were introduced.

Saturday, October 1, 2022
 
macca1
 
4

Do you mean something like:

foreach($_POST['something'] as $key => $something) { 
    $example = $_POST['example'][$key];
    $query = mysql_query("INSERT INTO table (row, row2) VALUES ('{$something}','{$example}')"); 
} 
Sunday, December 11, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :