Find and Return List of Even and Odd Numbers

Hello All, Need help in solving this task.
The returned Array should be in this format:

array(
“even” => [2,4,6,8,10,12,14]
“odd” => [1,3,5,7,9,11,13]
)

    function getEvenAndOddNumbers($Arr) {

	}
	$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
	$result = getEvenAndOddNumbers($numbers);

Many thanks

If you want to learn to program with php you should try to find your own solution. From here i will give you some hints.

First inside your function you will have to walk through all members of $Arr. Read about a foreach on php.net.
Then for each element in $Arr you will have to determine if it is an odd or even value. You could use the Modulo operator.
Third. You need to return a new array with two elements: “even” and “odd” . To be sure to have them both start initializing the array with default values:

$result = array(
    'even' => array(),
    'odd' => array(),
);

You have now an array with the two elements Each of the two holds an empty array. The only thing you need to do is to add each element of the $Arr array to the “even” or “odd” element like so:

if(...) {
    $result['even'][] = ... ;
} else {
    $result['odd'][] = ... ;
}

You will have to fill in the dots.

At the end you will have to return the $result array. Good luck!

2 Likes

Thank you so much @frankbeen. I appreciate your help.

Here is the solution:
function getEvenAndOddNumbers($Arr) {
$result = array( 'even' => array(), 'odd' => array());
foreach($Arr as $key=>$value) {
if($value % 2 === 0) {
$result['even'][] = $value;
} else {
$result['odd'][] = $value;
}
}
return $result;
}
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$result = getEvenAndOddNumbers($numbers);
print_r($result);

Output:
Array (
[even] => Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 [5] => 12 [6] => 14 )
[odd] => Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 [4] => 9 [5] => 11 [6] => 13 )
)

Now, I would be interested to know, how to get the above output in the following format:

array (
"even" => [2,4,6,8,10,12,14]
"odd" => [1,3,5,7,9,11,13]

)

<?php

function oddCmp($input)
{
    return ($input & 1);
}

function evenCmp($input)
{
    return !($input & 1);
}

$numbers = range(1,14);
$odd = array_filter($numbers, "oddCmp");
$even = array_filter($numbers, "evenCmp");

echo '<pre>', print_r($odd), '</pre>';
echo '<pre>', print_r($even), '</pre>';
2 Likes

Well your output is technical the same as your example. The only difference is that the print_r function does not only show the values but also the array keys. Congratulations you have accomplished your exercise.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service