php - Sort array into alternating smallest largest values?

232

Does anyone know how to sort an array into alternating smallest largest values?

I.E.

Array (10, 2, 5, 1, 30, 1, 7)

Should be :

(30, 1, 10, 1, 7, 2, 5)

EDIT:

Forgot to mention the arrays are associative, so:

Array("A"=>10, "B"=>2, "C"=>5, "D"=>1, "E"=>30, "F"=>1, "G"=>7)

Should become:

("E"=>30, "D"=>1, "A"=>10, "F"=>1, "G"=>7, "B"=>2, "C"=>5)
280

Answer

Solution:

Sort your array then push elements from beginning and end of the array alternatively:

<?php

    $myArray = array(10, 2, 5, 1, 30, 1, 7);
    sort($myArray );
    $count=sizeof($myArray );

    $result= array();
    
    for($counter=0; $counter * 2 < $count; $counter++){

         array_push($result, $myArray[$count - $counter - 1]);
         //check if same elements (when the count is odd)
         if ($counter != $count - $counter - 1) {
             array_push($result, $myArray[$counter]);
         }

    }
    print_r ($result);

?>

returns:

Array ( [0] => 30 [1] => 1 [2] => 10 [3] => 1 [4] => 7 [5] => 2 [6] => 5 )
374

Answer

Solution:

<?php
$x = array(10, 2, 5, 1, 30, 1, 7);

// First sort
sort($x);

// Then pick highest and lowest from the back and front of the array
// until it is empty.
$z = array();
while (count($x) > 0){
    $z[] = array_pop($x);
    if (count($x) > 0) // <- For arrays with an odd number of elements.
      $z[] = array_shift($x);
}

var_dump($z);
757

Answer

Solution:

I can't tell you the exact syntax, my php is very rusty, but what you can do:

  • Sort your array in descending order

  • Split in in half, let say array A and B;

  • Create a new array and add each element from A and B in order$A[i], $B[count($B)-1-i]

This should give you what you need

7

Answer

Solution:

There is no predefined way to do this. However, php allows for a user sort function which you can customise to sort the array in the way you require.

People are also looking for solutions to the problem: php - Best way to query on all user profiles and collect them to show to a particular user in MySQL

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.