User26 User26 - 1 year ago 105
PHP Question

php - print even and (sorted) odd numbers of an array

I have an array given below

$array = array(50,51,52,53,54,55,56,57,58,59);

I am trying to print the values of array while even numbers will remain in same order and the odd numbers are sorted i.e. 59,57,55,53,51

The output should be like


I've separated the even and odd numbers in two diff variables. how should i proceed further ?

here is my code

$even= "";
$odd= "";

}else $odd.=$i.",";
echo $even.$odd;

Answer Source

Instead of pushing the evens and odds into a string, push them each into an array, sort the array with the odds in reverse and then loop through one of them (preferably through the even array) and add the even and the odd to a new array.

This is how I've done it:

$array = array(50,51,52,53,54,55,56,57,58,59);
$odds = array();
$even = array();
foreach($array as $val) {
    if($val % 2 == 0) {
        $even[] = $val;
    } else {
        $odds[] = $val;


$array = array();
foreach($even as $key => $val) {
    $array[] = $val;
    if(isset($odds[$key])) {
        $array[] = $odds[$key];

But you should be cautious if you have less even than odd numbers, as the loop will finish before all odds are added. You can check for that either before or after you've filled the new array. If you check after filling the new array, you can use array_diff and array_merge to add the missing odds to the new array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download