Foreach is only returning the first value of an array - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Saturday, June 5, 2021

Foreach is only returning the first value of an array

I don't understand why foreach is only returned the first value from the $even_values array. Here is the full code.

class fibonacci {

    private $seq_value;
    private $sequence = array(1,2);
    private $even_values = array();

    public function __construct(int $seq_value){
    $this->seq_value = $seq_value;
    }

    
    public function fibonacci_sequence(){
       for ($i=0; $i<=$this->seq_value-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();


source https://stackoverflow.com/questions/67842723/foreach-is-only-returning-the-first-value-of-an-array

No comments:

Post a Comment