Dodo - 1 year ago 58

PHP Question

I tried to write a PHP code which delete the first few odd numbers until the next number is even with using loop.

Printing the Fibonacci series works, but it does not delete first few odd numbers.

My Fibonacci numbers:

`1 1 2 3 5 8 13 21 34 55 89 144 233 377`

And the result what I would like to print out:

`2 3 5 8 13 21 34 55 89 144 233 377`

My code:

`<?php`

$fibarray = array(1, 1);

$fibarray[2] = $fibarray[0] + $fibarray[1];

for ( $i=2; $i<=13; ++$i ) {

$fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];

}

foreach ($fibarray as $final) {

for ($i=0; $i<=15; $i++) {

if ($fibarray[$i]%2 != 0) {

unset($fibarray[$final]);

}

}

echo $final.' ';

}

?>

Can you help me how to solve this?

Answer Source

you can iterate the array to find first even num. here is the demo.

```
$fibarray = array(1, 1);
$fibarray[2] = $fibarray[0] + $fibarray[1];
for ( $i=2; $i<=13; ++$i ) {
$fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];
}
//$array = array(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377);
$array = $fibarray;
$index = 0; $length = count($array);
for(; $index < $length; $index++)
{
if( ($array[$index] & 1) == 0)
break;
}
$resultArray = array_slice($array, $index);
echo implode(' ', $resultArray )."\n";
```