w3resource

PHP Exercises: Create a new array of given length using the odd numbers from a given array of positive integers


136. New Array from Odd Numbers with Given Length

Write a PHP program to create a new array of given length using the odd numbers from a given array of positive integers.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers 'nums' and an integer 'count'
function test($nums, $count)
{ 
    // Initialize an array 'evens' to store odd numbers, with size 'count'
    $evens = [$count];
    
    // Initialize a variable 'j' to track the index in the 'evens' array
    $j = 0;

    // Use a for loop to iterate through the elements of 'nums'
    for ($i = 0; $j < $count; $i++)
    {
        // Check if the current number is odd
        if ($nums[$i] % 2 != 0)
        {
            // If true, store the odd number in the 'evens' array and increment 'j'
            $evens[$j] = $nums[$i];
            $j++;
        }
    }

    // Return the resulting 'evens' array
    return $evens;
}

// Call the 'test' function with an example input and display the result
$result = test([1,2,3,5,7,9,10], 3);
echo "New array: " . implode(",", $result);
?>

Sample Output:

New array: 1,3,5

Flowchart:

Flowchart: Create a new array of given length using the odd numbers from a given array of positive integers.

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract odd numbers from an input array and return a new array of a specified length.
  • Write a PHP function to filter an array for odd integers and then take the first n odd numbers to form a new array.
  • Write a PHP program to iterate through an array, select odd values, and stop when the new array reaches the required size.
  • Write a PHP script to use array_filter() to gather odd numbers and then use array_slice() to return an array of given length.

Go to:


PREV : Check if Integer Contains Digit 2.
NEXT : PHP Exception Handling Exercises Home.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.