1

Trying to change just TWO values of array from string to integer (in order to do math on them)

Tried:

echo (float)$final_data[0][0][4] - (float)$final_data[0][0][2];
echo "<br>";
echo (float)($final_data[0][0][4] - $final_data[0][0][2])/$final_data[0][0][2]*100;

Does not work. It still outputs '2' which is the string talking.

Is there a way to do this? I know how to transform ALL of the array into integers but is there an easy way to just do it per element like I'm doing?

EGP
  • 387
  • 1
  • 4
  • 12

2 Answers2

3

Settype sets the data type of variable to specified type. settype($final_data[0][0][4],'int');. If you want to know the data type of a variable than you can use echo gettype($final_data[0][0][4]);. Hope this helps

Yojan
  • 159
  • 1
  • 10
2

Yes, you can do it. First of all, you can't cast after the operation so (float)this - (float)this would be closer, but you should use floatval to do the conversion.

echo floatval( $final_data[0][0][4] ) - floatval( $final_data[0][0][2] );
echo "<br>";
echo ( floatval($final_data[0][0][4] ) - floatval( $final_data[0][0][2] ) ) / floatval( $final_data[0][0][2] ) * 100;
JasonB
  • 6,243
  • 2
  • 17
  • 27
  • May I ask what you mean by 'casting after the operation'? – EGP Jan 17 '18 at 06:02
  • https://stackoverflow.com/questions/30940148/typecasting-vs-function-to-convert-variable-type-in-php says that casting is faster, I use floatval() to avoid some errors from bad data – JasonB Jan 17 '18 at 06:03
  • 1
    (float)(x - y) is casting after the subtraction operation - it won't work right. (float)x - (float)y is casting the operands and then carrying out the operation. – JasonB Jan 17 '18 at 06:04