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?

1
  • Give sample data of $final_data Commented Jan 17, 2018 at 6:00

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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;

3 Comments

May I ask what you mean by 'casting after the operation'?
stackoverflow.com/questions/30940148/… says that casting is faster, I use floatval() to avoid some errors from bad data
(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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.