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 ie 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];
}
}
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.
Following code will run as per the odd number count. There won't be any loop count issue.
function oddNumber($num){
return $num % 2 == 1;
}
$givenArray = array(50, 51, 52, 53, 54, 55, 56, 57, 58, 59);
$oddArray = array_filter($givenArray, "oddNumber");
rsort($oddArray);
$finalArray = array();
$oddCount = 0;
foreach($givenArray as $num){
if(oddNumber($num)){
$finalArray[] = $oddArray[$oddCount];
++$oddCount;
}else{
$finalArray[] = $num;
}
}
print_r($finalArray);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.