简体   繁体   中英

How to output unique values from arrays without array functions?

I need to output unique values from two arrays, but I can't use any array functions only foreach and if statement. As result should return one array with unique values and the converted to string.

I tried to equal two values but output is not I excepted.

function uniqueNames(array $array1, array $array2){
    $output = [];
    foreach($array1 as $name1) {
        foreach($array2 as $name2) {
            if ($name1 !== $name2){
                $output[] = $name1." ";
            } 
        }
    }
    return implode(",", $output);
}

print_r(uniqueNames(['July', 'Ringold'], ['Harison', 'July', 'Antony']));```

My expected results are July, Ringold, Harison, Antony
But I get July ,July ,Ringold ,Ringold ,Ringold

The problem is that you are comparing each item against every item in the next array and adding the value from the first array for each item that doesn't match.

This solution uses the fact that all keys for an array are unique, so first it loops over all of the arrays and adds them into a cumulative array ( $unique ) and then loops over this and gets all of the key values as the list of unique values ( $output )...

function uniqueNames(array $array1, array $array2){
    $unique = [];
    $output = [];
    foreach([$array1, $array2] as $sub) {
        foreach($sub as $name2) {
            $unique[$name2] = null;
        }
    }
    foreach ( $unique as $key => $value )   {
        $output[] = $key;
    }
    return implode(",", $output);
}

Alternatively using if , what you have to do is loop over the one array and then check against the all of the elements in the other array. Only when you can't find it can you say it needs to be added. This just uses a flag which is changed when the item is found....

function uniqueNames(array $array1, array $array2){
    $output = $array1;
    foreach($array2 as $name2) {
        $found = false;
        foreach($array1 as $name1) {
            if ($name1 == $name2){
                $found = true;
                break;
            }
        }
        if (!$found)   {
            $output[] = $name2;
        }
    }
    return implode(",", $output);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM