User26 - 2 months ago 16x
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

``````50,59,52,57,54,55,56,53,58,51
``````

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

here is my code

``````  \$even= "";
\$odd= "";

for(\$i=50;\$i<=59;\$i++)
{
if(\$i%2==0)
{
\$even.=\$i.",";
}else \$odd.=\$i.",";
}
echo \$even.\$odd;
``````

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;
}
}

sort(\$even);
rsort(\$odds);

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

https://3v4l.org/2hW6T

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.