Industrial
Industrial

Reputation: 42758

PHP - Check that value doesn't appear twice in array

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?

Upvotes: 2

Views: 2550

Answers (2)

shrmn
shrmn

Reputation: 1513

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)

Upvotes: 1

Amber
Amber

Reputation: 526593

$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.

Upvotes: 3

Related Questions