2

I need to check if a value in an array is_float(). But when I output the array with var_dump() every decimal is recognized as string:

$sql = "SELECT * FROM table WHERE id = :mainID";

$result = $db->prepare($sql);
$result->bindParam(":mainID", $mainID, PDO::PARAM_INT);

$result->execute();
$mainData = $result->fetch();   

var_dump($mainData);

Part of the var_dump Output:

["price"]=> string(6) "188.02"

Why isn't this value recognized as float, even though the column type in the DB is decimal?

Edit: Please note, that this question is about decimals. I don't care about INT values.

KHansen
  • 784
  • 5
  • 21
  • 2
    PHP typecasts variables run time. So, even if you have defined a field `float` in database, PHP will interpret it as string if the current value assigned to it is a string. – Pupil Mar 14 '19 at 06:18
  • All results from SQL are returned as strings in PHP, regardless of what type the column was. – Qirel Mar 14 '19 at 06:19
  • @Pupil, @Qirel, Thanks. In that case, how can I achieve to check if the value `is_float()`? – KHansen Mar 14 '19 at 06:22
  • http://php.net/manual/en/pdostatement.bindcolumn.php – Pinke Helga Mar 14 '19 at 06:23
  • @trincot Why did you mark this as duplicate? As stated in one of the comments: "Note that even with this version of mysqlnd enabled, DECIMALS will still be sent as strings... " – KHansen Mar 14 '19 at 06:38
  • 1
    Although the referenced questions focus more on integers, the subject specific to decimals is covered. I added one more reference that specifically asks about decimals. Sometimes the answer is not what we hope for. In essence, a decimal is not a float. The first has exact precision, the second not, so a precise conversion would not be possible and therefore not desired. It is up to the client (you) to make that conversion if you don't care about the potential loss of precision. – trincot Mar 14 '19 at 07:38
  • @trincot Yeah, you're right. Thanks. – KHansen Mar 14 '19 at 07:54

0 Answers0