Showing posts with label PHP asort. Show all posts
Showing posts with label PHP asort. Show all posts

Thursday, 30 August 2018

PHP sort array comparing the value and pushing the smaller values ​​last


I have a value and comparing that value i want to change order of an array


for eg. here 3 is value so i need array order to be
5,6,1,2
so values less then 3 shifts last in array.
<?php

$value=3;

$array=array(6,2,5,1);

asort($array);

print_r($array);

?>


Please have a look on the below code, it may help you. You need to use array_filter with call back function to make 2 arrays then u can merge them.
  $value=3;
  $array=array(6,2,5,1);
  asort($array);
  $right = array_filter($array, function($elem) use($value){
      return $elem < $value;
  });
  $left = array_filter($array, function($elem) use($value){
     return $elem > $value;
  });
  //print_r($right);
  //print_r($left);
  $res = array_merge($left,$right);
  print_r($res);

Thursday, 25 September 2014

asort in PHP

asort() function is utilized to sort an input array by the values. The keys relating to the values are kept as same.
The PHP asort() function returns TRUE on success, or FALSE on failure.

Syntax:

asort(array,sorttype)
 
Parameters Description: 
array : Required. Specifying an array
sorttype : Optional. Specifies how to sort the array values.
     Possible values:
  • SORT_REGULAR - Default. Treat values as they are (don't change types)
  • SORT_NUMERIC - Treat values numerically
  • SORT_STRING - Treat values as strings
  • SORT_LOCALE_STRING - Treat values as strings, based on local settings

Example:

<?php  
$daysarr1 = array( "a"=>"Sunday","b"=>"Monday","c" =>"Tuesday" );
asort($daysarr1);
print_r($daysarr1);
?>

Output will be:

Array (
         [b] => Monday 
         [a] => Sunday
         [c] => Tuesday
       )