w3resource

PHP Exercises: Check if one of the first 4 elements in an array of integers is equal to a given element


Write a PHP program to check if one of the first 4 elements in an array of integers is equal to a given element.

Sample Solution:

PHP Code :

<?php
// Define a function that checks if a given number is present in an array of numbers
function test($nums, $n)
{
    // Use the sizeof function to check the size of the array and determine the range for in_array
    return sizeof($nums) < 4 ? in_array($n, $nums) : in_array($n, array_slice($nums, 0, 4));
}

// Test the function with different arrays and numbers
var_dump(test(array(1,2,9,3), 3));
var_dump(test(array(1,2,3,4,5,6), 2));
var_dump(test(array(1,2,2,3), 9));
?>

Explanation:

  • Function Definition:
    • The test function takes two parameters: an array of numbers $nums and a number $n to search for in the array.
  • Check Array Size:
    • sizeof($nums) checks the length of the array.
    • If the array length is less than 4, the function checks if $n is present in the entire array using in_array().
  • Check First Four Elements:
    • If the array length is 4 or more, the function only checks if $n is in the first four elements by using array_slice($nums, 0, 4) to extract those elements.
    • in_array($n, array_slice($nums, 0, 4)) then checks for $n in this slice.

Output:

bool(true)
bool(true)
bool(false)

Visual Presentation:

PHP Basic Algorithm Exercises: Check if one of the first 4 elements in an array of integers is equal to a given element.

Flowchart:

Flowchart: Check if one of the first 4 elements in an array of integers is equal to a given element.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a PHP program to check a specified number is present in a given array of integers.
Next: Write a PHP program to check whether the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere.

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.