PHP Exercises: Create a new array taking the elements after the element value 5 from a given array of integers
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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics