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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.