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);
?>

Explanation:

  • Function Definition:
    • A function named test is defined, which takes one parameter:
      • $numbers: an array of numbers.
  • Loop through Array:
    • The function uses a for loop to iterate through the array, stopping at the second-to-last element ($i < sizeof($numbers) - 1).
  • Condition Check:
    • During each iteration, the function checks if:
      • The current element is 5 ($numbers[$i] == 5).
      • The next element is 7 ($numbers[$i + 1] == 7).
    • If both conditions are true, the next element is set to 1 ($numbers[$i + 1] = 1).
  • Return Modified Array:
    • The function returns the modified version of the array.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-98.php