phparraysdivisionfactoringsynthetic

PHP array values not being changed


I was trying to make a program to do synthetic division which requires factoring so I wrote this function to factor an integer which works, but it never changes the values of the php array $factors. Any help will be greatly appreciated.

$factors=array();
$i;
function factor($x){
    if($x==0){
        echo "(0,0)";
        } else {
            $n=false;
            if($x<0) {
                $x=abs($x);
                $n=true;
            }
            for($i=2; $i<=$x; $i++) {
                if($x%$i==0){
                    if($n){
                        $factors[(count($factors))]=(-1*($x/$i));
                        $factors[(count($factors))]=($i);
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=(-1*$i);
                    } else {
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=($i);
                    }
                }
            }
        }
    }
factor(-4);

Solution

  • Try this

    function factor($x){
         $factors=array();
        if($x==0){
            echo "(0,0)";
        } else {
            $n=false;
            if($x<0) {
                $x=abs($x);
                $n=true;
            }
            for($i=2; $i<=$x; $i++) {
                if($x%$i==0){
                    if($n){
                        $factors[(count($factors))]=(-1*($x/$i));
                        $factors[(count($factors))]=($i);
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=(-1*$i);
                    } else {
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=($i);
                    }
                }
            } //end for
           echo '(' . implode(',', $factors). ')';
        } //end if $x == 0
    }
    factor(-4);
    

    $factors is outside the scope of the function, besides that you were not returning or outputting anything. Seeing as you echo (0,0) I assumed you wanted it echoed such as (2,4,8) etc. Which you can do with implode..