w3resource
w3resource logo

PHP Exercises: Check if an array of integers contains a 3 next to a 3 or a 5 next to a 5 or both

(追記) (追記ここまで)
(追記) (追記ここまで)

116. Contains Adjacent 3's or 5's Check

Write a PHP program to check if an array of integers contains a 3 next to a 3 or a 5 next to a 5 or both.

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 elements of the array up to the second-to-last element
 for ($i = 0; $i < sizeof($numbers) - 1; $i++) { // Check if there are consecutive occurrences of either 3 and 3 or 5 and 5 if (($numbers[$i] == 3 && $numbers[$i + 1] == 3) || ($numbers[$i] == 5 && $numbers[$i + 1] == 5)) return true; } // Return false if there are no consecutive occurrences of either 3 and 3 or 5 and 5 return false; } // Use 'var_dump' to print the result of calling 'test' with different arrays var_dump(test([5, 5, 5, 5, 5])); var_dump(test([1, 2, 3, 4])); var_dump(test([3, 3, 5, 5, 5, 5])); var_dump(test([1, 5, 5, 7, 8, 10])); ?> 

Sample Output:

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

Flowchart:

Flowchart: Check if an array of integers contains a 3 next to a 3 or a 5 next to a 5 or both.

For more Practice: Solve these Related Problems:

  • Write a PHP script to verify if an array contains at least one pair of adjacent 3's or a pair of adjacent 5's.
  • Write a PHP function to scan through an array and return true if two identical numbers (either 3 or 5) appear consecutively.
  • Write a PHP program to use a loop to check each pair of adjacent elements for the values 3 or 5, returning a boolean if found.
  • Write a PHP script to determine if the array contains consecutive identical pairs of 3’s or 5’s by comparing indices.

Go to:


PREV : Array Contains No 3 or 5 Check.
NEXT : Array Contains Two 5's Next to or Separated by One.

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.

(追記) (追記ここまで)


(追記) (追記ここまで)
(追記) (追記ここまで)


AltStyle によって変換されたページ (->オリジナル) /