Arrays

I am having some trouble with arrays. I do not think my arrays are initializing. I an getting zero for sumx. Could someone take a look?

class class1 {
     function SUM(){
          $this->x = array(0,1,2,3,4,5,6);
          for ($this->k = 0; $this->k <= 6; $this->k++){
               $this->sumx += $this->x[k];
          }
     }
}

your variable(x,k,sumx) not declared

Are you expecting a return from the function SUM()? If so there is no return command. (return $this->sumx; )

Also for your code, foreach is a better alternative as it’s easier to read/understand. Or you can use a predefined php function (array_sum), though I assume you’re just doing this for learning.

Another thing, don’t use one letter variables like x and k together -_-, very hard to read and easily confusing.

This line:
$this->sumx += $this->x[k];

should be this:
$this->sumx += $this->x[$this->k];

or update your code to this:

<?php
   class class1 {
	   function SUM(){
		   $this->x = array(0,1,2,3,4,5,6);
		   for ($k = 0; $k <= 6; $k++){
			   $this->sumx += $this->x[$k];
		   }
		   return $this->sumx;
	   }
   }
   $sum = new class1();
   $total = $sum->SUM();
   echo $total;
?>

Corrected the $this->k but still does not work.

Works fine when I ran tom8’s code.

You don’t have to declare variables in PHP; it’s not Java :slight_smile: