Sort php array returning new array

I am looking for a reliable standard method for sorting an array, returning a sorted (associative) array as the return value .

All PHP.net functions that I read about returning a BOOLEAN value, or 0-1. I need a way:

$some_mixed_array = array( 998, 6, 430 ); function custom_sort( $array ) { // Sort it // return sorted array } custom_sort( $some_mixed_array ); // returning: array( 6, 430, 998 ) 

No need to process strings, just INT-s.

+8
source share
3 answers

Could you do that?

 $some_mixed_array = array( 998, 6, 430 ); function custom_sort( $array ) { // Sort it asort($array); // return sorted array return $array; } custom_sort( $some_mixed_array ); // returning: array( 6, 430, 998 ) 

This will also solve your problem:

 $some_mixed_array = array( 998, 6, 430 ); echo '<pre>'.print_r($some_mixed_array, true).'</pre>'; asort($some_mixed_array); // <- BAM! // returning: array( 6, 430, 998 ) echo '<pre>'.print_r($some_mixed_array, true).'</pre>'; 
+4
source

Here's a single line:

call_user_func(function(array $a){asort($a);return $a;}, $some_mixed_array);

+3
source

As others have said, it’s best to create your own function. However, to maintain flexibility in the future of PHP, I would use a variable function . In essence, you set your function so that it accepts any parameters passed to it and passes them to the actual sort() function. Thus, you can use any optional parameters for the standard function that you put in the shell, even if these parameters change in the future.

 function mysort( ...$params ) { sort( ...$params ); return $params[0]; } 
0
source

Source: https://habr.com/ru/post/1501480/


All Articles