Jump to content

Sorting


Alicia

Recommended Posts

<?php
function whatever($input){
$input = (string)$input;
$input = substr($input,-1,1).substr($input,-2,1).substr($input,0,1);
return (int)$input;
}
echo whatever(762);
?>

 

 

That's not quite what the OP was asking. It works for the specific value mentioned, but it doesn't work if the input is "726" for example.

 

Instead, you could try something like:

 

<?php
function whatever($input){
//INITIALIZE VARIABLES
$num_array = array();

//BREAK APART THE INPUT STRING
for($i=0; $i<strlen($input); $i++) {
	$num_array[] = substr($input, $i, 1);
}

//SORT THE ARRAY AND RETURN THE RESULTS
sort($num_array);
return implode($num_array);
}

echo whatever($_GET['input']);
?>

Link to comment
https://forums.phpfreaks.com/topic/244477-sorting/#findComment-1255822
Share on other sites

Instead of using a for loop and substr, alternatively you can take advantage of str_split, my take:

 

function dontKnowWhatToNameThis($n) {
    $split = str_split($n);
    sort($split);
    return implode($split);
}

 

Was going to post exactly the same earlier, but assumed the manix's version worked just fine when I tested it with only the given test value :P Good feature in this method is also that the number can be longer or shorter than 3 digits and it still works.

Link to comment
https://forums.phpfreaks.com/topic/244477-sorting/#findComment-1255898
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.