w3resource

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


125. Array Elements Before Value 5

Write a PHP program to create a new array taking the elements before 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)
{ 
    // Initialize variables to store the size and elements before the first occurrence of '5'
    $size = 0;
    $pre_ele_5;

    // Iterate through the elements of the input array using a for loop
    for ($i = 0; $i < sizeof($numbers); $i++)
    {
        // Check if the current element is equal to '5'
        if ($numbers[$i] == 5)
        {
            // Set the size to the current index and break out of the loop
            $size = $i;
            break;
        }
    }

   // Initialize an empty array to store the elements before the first occurrence of '5'
    $pre_ele_5 = [];

    // Iterate through the elements before the first occurrence of '5'
    for ($j = 0; $j < $size; $j++)
    {
        // Copy the elements to the 'pre_ele_5' array
        $pre_ele_5[$j] = $numbers[$j];
    }

    // Return the array containing elements before the first occurrence of '5'
    return $pre_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] );

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

Sample Output:

New array: 1,2,3 

Flowchart:

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

For more Practice: Solve these Related Problems:

  • Write a PHP script to scan an array and output a new array containing only the elements that appear before the first occurrence of 5.
  • Write a PHP function to iterate through an array and stop adding elements to the new array upon encountering the number 5.
  • Write a PHP program to use a loop to collect all elements until a 5 is encountered and then return that subarray.
  • Write a PHP script to check for the value 5 and slice the array before that index to form the result.

Go to:


PREV : Shift Array Elements Left.
NEXT : Array Elements After Value 5.

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.