w3resource

PHP Exercises: Check a given array of integers, length 3 and create a new array

PHP Basic Algorithm: Exercise-98 with Solution

Write a PHP program to check a given array of integers, length 3 and create a new array. If there is a 5 in the given array immediately followed by a 7 then set 7 to 1.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
 { 
    // Iterate through the array up to the second-to-last element
    for ($i = 0; $i < sizeof($numbers) - 1; $i++)
    {
        // Check if the current element is 5 and the next element is 7
        if ($numbers[$i] == 5 && $numbers[$i + 1] == 7)
            // If true, set the value of the next element to 1
            $numbers[$i + 1] = 1;
    }
    // Return the modified array
    return $numbers;
 }   

// Create an array $a with numeric values
$a = [1, 5, 7];

// Print the original array as a string using 'implode' and 'echo'
echo "Original array: " . implode(',', $a) . "\n";

// Call the 'test' function with the array $a and store the result in $result
$result = test($a);

// Print the new array after applying the modification using 'implode' and 'echo'
echo "New array with maximum values: " . implode(',', $result);
?>

Sample Output:

Original array: 1,5,7
New array with maximum values: 1,5,1

Flowchart:

Flowchart: Check a given array of integers, length 3 and create a new array.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check a given array of integers and return true if the array contains 10 or 20 twice. The length of the array will be 0, 1, or 2.
Next: Write a PHP program to compute the sum of the two given arrays of integers, length 3 and find the array which has the largest sum.

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.