Q:

Write a PHP program to check a given array of integers and return true if every 5 that appears in the given array is next to another 5

0

Write aPHP program to check a given array of integers and return true if every 5 that appears in the given array is next to another 5

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
function test($numbers)
 { 
     $arr_len = sizeof($numbers);
     $flag = true;

        for ($i = 0; $i < $arr_len; $i++)
            {
                if ($numbers[$i] == 5)
                {
                    if (($i > 0 && $numbers[$i - 1] == 5) || ($i < $arr_len - 1 && $numbers[$i + 1] == 5)) $flag = true;
                    else if ($i == $arr_len - 1) $flag = false;
                    else return false;
                }
            }
            return $flag;
 }   

var_dump(test([3, 5, 5, 3, 7]));
var_dump(test([3, 5, 5, 4, 1, 5, 7]));
var_dump(test([3, 5, 5, 5, 5, 5]));
var_dump(test([2, 4, 5, 5, 6, 7, 5]));

Sample Output:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now