Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo json_encode($return_data, JSON_NUMERIC_CHECK); character 'e' in digits not working

one of row of my db has contacts table has character varying column as phone with value 3162e6313358

$return_data = array('phone' => $contact_phone);
echo json_encode($return_data, JSON_NUMERIC_CHECK);

this code does not give me any output. I searched for this people gave solutions like ('phone' => '".$contact_phone."') this is working. I don't want to typecast for every array element But i need generic solution.

Thanks.

like image 900
mahesh kajale Avatar asked Nov 01 '22 11:11

mahesh kajale


1 Answers

Option 1 (the best)

  1. Convert numeric values (IDs, counts, numeric status codes, booleans a.s.o.) to numbers as soon as you get them from user input ($_GET[], $_POST[]) or from database. When they are extracted from user input the conversion should be part of the data validation anyway.

  2. Keep phone "numbers" as strings; they are not numbers, after all, they are just strings of digits, with or without starting zeroes and non-digit characters in the middle or at the end. Also keep as strings other values that looks numeric but are, in fact, not numbers: credit card numbers, for example.

  3. Remove the JSON_NUMERIC_CHECK parameter from the call to json_encode(); if you implement #1 above you don't need it any more.

Option 2 (workaround)

Append a space character (' ') to the phone number when you get it from the database. It won't make much difference (if any at all) when it is displayed in a web page.

json_encode() won't believe it is a floating point number any more, not even if it starts with + or 0.

like image 166
axiac Avatar answered Nov 08 '22 07:11

axiac