Home > Software engineering >  Printing numers without using PHP inbuild functions
Printing numers without using PHP inbuild functions

Time:05-23

$numbers = array(3,5,6,7,8,11);
$missing = array();
for ($i = 3; $i < 11; $i  ) {
    if (!in_array($i, $numbers)){
        $missing[] = $i;
    }
}

I want to find the missing numbers from 3 to 11 without using PHP innuild function, i have tried but i haven't not completed fully.

In this code i have used in_array but without this i have to do. any one help here.I am new to PHP using PHP inbuild i can do this, but this is not my case.

CodePudding user response:

Use foreach loop inside on $numbers and check for the value of $i. Declare a flag variable, say $found to false. While looping inside if we get the number, set $found to true and exit the loop. In the end, if $found still stays as false, add the current $i to the result.

<?php

$numbers = array(3,5,6,7,8,11);
$missing = array();

for ($i = 3; $i <= 11; $i  ) {
    $found = false;
    foreach($numbers as $value){
        if($value === $i){
            $found = true;
            break;
        }
    }
    
    if(!$found) $missing[] = $i;
}


print_r($missing);

Online Demo

CodePudding user response:

you can use array_diff same as :


$numbersOrigin = range(3, 11);
$numbers = array(3,5,6,7,8,11);

$missing = array_diff($numbersOrigin, $numbers);

unuse buildIn functions :

$numbers = array(3,5,6,7,8,11);
$missing = array();
$index = 0;
for ($i = 3; $i < 11; $i  ) {
   if ($numbers[$index] === $i) {
         $index  ;
   } else {
      $missing[] = $i;
   }
}

  •  Tags:  
  • php
  • Related