0

//Procedural Works!!

$x=0;

$e1=$x/450+1/2; $e2=$x==0?false:6300/$x;

while($e1 !== $e2){ 

  ++$x; 

  $e1=$x/450+1/2; $e2=$x==0?false:6300/$x;

  if($e1 == $e2){
  echo "x Solution:  ". $x . "<br>y Solution:  ".$e1;
  exit;
  }

}

//Function fails on e2 WHY????? I'm done banging my head against the wall on this. I have researched eval but I don't know why e2 fails....

function eSolver($eq1,$eq2){

$x=0;

$e1=eval("return $eq1;"); $e2=eval("return $eq2;");
/*
while($e1 !== $e2){ 

  ++$x; 

  $e1=$eq1; $e2=$eq2;

  if($e1 == $e2){
  $ePoint= "x Solution:  ". $x . "<br>y Solution:  ".$e1;
  exit;
  }

}
*/
return $e2;
}

$supply=$x/450+1/2; $demand=$x==0?false:6300/$x;

echo eSolver($supply,$demand);

//e1 works not e2 and if e2 does not work, the whole function is pointless.

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

When you say

$supply=$x/450+1/2; $demand=$x==0?false:6300/$x;

those values are getting calculated then and there, not within the function. You need to wrap them, whether in quotes to pass to eval (ick) or in an anonymous function.

$supply = function($x) { return $x/450 + 1/2; };
$demand = function($x) { return ($x == 0) ? false : 6300/$x; };

Once they're lambdas, you don't need to eval anything -- and in fact, i'm not sure you even can. So get rid of the evals.

Now, within your loop in eSolver, you can say like

$e1 = $eq1($x); $e2 = $eq2($x);

to evaluate them.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • Thank you. I had seen functional coding in Javascript but had never thought of implementing it or did I know how in PHP. It's really no different than Javascript anonymous functions. I will implement anonymous functions instead of eval() You are correct. You can't implement using eval. I stayed up for hours last night until I had to go to bed. Thanks so much again! – Jorge Guerrero Oct 26 '17 at 22:08
  • You can implement it using `eval`, but it's a wrongheaded approach. When you know what you want to calculate, it's better off as a function than a string. – cHao Oct 26 '17 at 22:17
  • Just finished testing the code, had to move the return statement to the if true conditional, but it worked, worked even better than procedural, and that's awesome. Functional coding, baby, a whole new level for me. Ye have lifted the blindness of ignorance :D – Jorge Guerrero Oct 26 '17 at 22:40