I don't understand why foreach is only returned the first value from the $even_values array:
Here is the value of $this->sequence array when I print readable on the fibonacci_sequence method:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 [4] => 8 [5] => 13 [6] => 21 [7] => 34 [8] => 55 [9] => 89 )
So I'm trying to use the return array from fibonacci_sequence method on the even_values method.
Here is the full code:
class fibonacci {
private $seq_limit;
private $sequence = array(1,2);
private $even_values = array();
public function __construct(int $seq_limit){
$this->seq_limit= $seq_limit;
}
public function fibonacci_sequence(){
for ($i=0; $i<=$this->seq_limit-3; $i++) {
$this->sequence[] = $this->sequence[$i] + $this->sequence[$i+1];
}
return $this->sequence;
//print_r($this->sequence);
}
public function even_values(){
foreach ($this->sequence as $value) {
if ($value % 2 == 0) {
$this->even_values[] = $value;
}
}
//return $this->even_values;
print_r($this->even_values);
}
}
$fibonacci = new fibonacci(10);
$fibonacci->even_values();
$this->sequenceis an array with values 1 and 2. Only one of those two is even, so you only get one of those (2) added tothis->even_values, which is output. What is your doubt?fibonacci_sequenceat some point?