mardi 2 novembre 2021

Loop through array of values and sort

I would like you to help me with an algorithm in PHP that can loop through an array of values, sort them and print non-duplicates.

Here is the code I wrote. I want to do it with only loop and if else statement. I would appreciate any help in achieving this. Thanks


    $input_array = [3, 5, 7, 7, 8, 3, 1, 9, 9, 9, 0, 2, 4, 8, 0, 12, 5, 8, 2];`
    $count_array = count($input_array); // count the array`enter code here`
    for($i = 0; $i < $count_array; $i++){ //loop through the array 1st time
        $check_array = false;
       
        //sort array
        for($j = $i+1; $j < $count_array; $j++){
           
            if($input_array[$i] > $input_array[$j]){
                $non_duplicates = $input_array[$i];
                $input_array[$i] = $input_array[$j];
                $input_array[$j] = $non_duplicates;
                    
            }
    
            else if($input_array[$i] == $input_array[$j] &&( $i != $j)){ 
                $check_array = true;
                break;
            }
    
            else{
                $input_array[$i] != $input_array[$j];
            }
    
        }  
    
         if(!$check_array){
            echo($input_array[$i]. ', ');
         }   
        
    }

Aucun commentaire:

Enregistrer un commentaire