0

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();

2
  • $this->sequence is an array with values 1 and 2. Only one of those two is even, so you only get one of those (2) added to this->even_values, which is output. What is your doubt? Commented Jun 4, 2021 at 19:05
  • 1
    Did you mean to call fibonacci_sequence at some point? Commented Jun 4, 2021 at 19:06

1 Answer 1

1

You seem to have forgotten to invoke the $fibonacci->fibonacci_sequence(); method to change the $sequence array, so do:

$fibonacci = new fibonacci(10);
$fibonacci->fibonacci_sequence();
$fibonacci->even_values();

demo

As suggested by @AbraCadaver, you can also call it from the constructor if it should always be populated:

public function __construct(int $seq_value)
{
    $this->seq_value = $seq_value;
    $this->fibonacci_sequence(); // <---------- ADD HERE
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, or call it from the constructor if it should always be populated.
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 the fibonacci_sequence method on the even_values method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.