Skip to content

Instantly share code, notes, and snippets.

@vladimirlukyanov
Created May 11, 2020 14:58
Show Gist options
  • Save vladimirlukyanov/0dfae9e55305213884260e2e5239da1c to your computer and use it in GitHub Desktop.
Save vladimirlukyanov/0dfae9e55305213884260e2e5239da1c to your computer and use it in GitHub Desktop.
Implement a function distinct(...), which expects an array of integers and sorts these ascendingly. The array shall not contain repetitions of any integer value but '1'. Repetitions of '1' should be the last values of the array.
<?php
/**
* @param array $array
*
* @return array | false
*/
function distinct( array $arr ) {
if ( is_array( $arr ) ) {
// checking if we have value "1" in array and how many :
$_tmp_array = array_count_values( $arr );
$count_val_in_array = isset($_tmp_array[1]) ? $_tmp_array[1] : false;
$arr = array_unique( $arr );
sort( $arr );
// If we have "1" in array, merge values to end of array :
if($count_val_in_array) {
for($i = 0 ; $i < $count_val_in_array - 1; $i++) {
array_push($arr, 1);
}
}
return $arr;
} else {
return false;
}
}
$test = array( 1, 21, 3, 44, 5, 1, 1, 1, 23, 4, 5, 5 );
print_r( distinct( $test ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment