w3resource

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


33. First Four Elements Array Element Match

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.

For more Practice: Solve these Related Problems:

  • Write a PHP script to check if any one of the first four elements in an array is equal to a given number.
  • Write a PHP function to compare a target value against the first four items of an integer array and return a boolean.
  • Write a PHP program to iterate over only the first four elements of an array and check for a match with a given integer.
  • Write a PHP script to use a for-loop with a limit of four iterations to test the presence of a specific number in an array.

Go to:


PREV : Specified Number in Array Check.
NEXT : Check for Sequence 1,2,3 in Array.

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.