views:

148

answers:

2

Hi,

I have a array inside my PHP app that looks like this:

Array
(
    [0] => Array
        (
            [name] => Name1
            [language] => 1
        )

    [1] => Array
        (
            [name] => Name2
            [language] => 1
        )

)

How can I check that "language" with value 1 doesnt appear twice, as effectively as possible?

+2  A: 
$dupe = 0;
foreach($yourarray as $key => $val) {
    if(array_key_exists($seen, $val['language'])) {
        // a duplicate exists!
        $dupe = 1;
        // could do other stuff here too if you want,
        // like if you want to know the $key with the dupe

        // if all you care about is whether or not any dupes
        // exist, you could use a "break;" here to early-exit
        // for efficiency. To find all dupes, don't use break.
    }
    $seen[$val['language']] = 1;
}

// If $dupe still = 0 here, then no duplicates exist.
Amber
A `break;` after `$dupe = 1;` would be good.
Matt
Either a `break` if only wanting to see if *any* dupes exist, or some other code if desired (for instance, one might want to find all of the dupes and record their positions, et cetera - I'm keeping this example general).
Amber
Hi Dav, thanks a lot. Do you think that it would be wiser to use ISSET instead of array_key_exist to save performance? Let me know what you think. Thanks!
Industrial
`array_key_exists` is the proper tool for the job - it *that* much slower than `isset` and is more readable in general.
Amber
+1  A: 

Tried the PHP function array_unique?

(Read the comments/user contributed notes below, especially the one by regeda at inbox dot ru, who made a recursive function for multi-dimensional arrays)

Sherman