w3resource

PHP Exercises: Create a new array taking the elements after the element value 5 from a given array of integers


126. Array Elements After Value 5

Write a PHP program to create a new array taking the elements after the element value 5 from a given array of integers.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
{ 
    // Get the length of the input array
    $len = sizeof($numbers);

    // Initialize variables to store the size and index
    $size = 0;
    $i = $len - 1;

    // Use a while loop to find the index of the last occurrence of '5' in the array
    while ($i >= 0 && $numbers[$i] != 5)
    {
        // Decrement the index until '5' is found or the beginning of the array is reached
        $i--;
    }

    // Increment the index to get the starting position of the array after the last occurrence of '5'
    $i++;

    // Calculate the size of the array after the last occurrence of '5'
    $size = $len - $i;

    // Initialize an array to store the elements after the last occurrence of '5'
    $post_ele_5 = [$size];

    // Iterate through the elements after the last occurrence of '5' and copy them to the new array
    for ($j = 0; $j < $size; $j++)
    {
        $post_ele_5[$j] = $numbers[$i + $j];
    }

    // Return the array containing elements after the last occurrence of '5'
    return $post_ele_5;
}   

// Call the 'test' function with an example array and store the result in the variable 'result'
$result = test([1, 2, 3, 5, 7, 9, 11] );

// Print the result array as a string
echo "New array: " . implode(',', $result);
?>

Sample Output:

New array: 7,9,11

Flowchart:

Flowchart: Create a new array taking the elements after the element value 5 from a given array of integers.

For more Practice: Solve these Related Problems:

  • Write a PHP script to create a new array consisting of all elements that occur after the first instance of the number 5.
  • Write a PHP function to iterate over an array and return a subarray starting immediately after the first 5.
  • Write a PHP program to use array slicing to capture all elements following the first occurrence of 5.
  • Write a PHP script to conditionally output the tail of an array starting from the index of the first detected 5.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new array taking the elements before the element value 5 from a given array of integers.
Next: Write a PHP program to create a new array from a given array of integers shifting all zeros to left direction.

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.