w3resource

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

PHP Basic Algorithm: Exercise-125 with Solution

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 array to store the elements before the first occurrence of '5'
    $pre_ele_5 = [$size];

    // 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.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to shift an element in left direction and return a new array.
Next: Write a PHP program to create a new array taking the elements after the element value 5 from a given array of integers.

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.