Advertisement
Guest User

JSON Parsing and Empty Value Checking

a guest
Aug 16th, 2018
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.07 KB | None | 0 0
  1. <?php
  2. header('Content-Type: text/plain');
  3. $json_string = '[{"highest_education":"B.E ( Automobile Engineering )","occupation":"Job in Private Office","annual_income":""}]';
  4.  
  5. function method1($json_string) {
  6.     $json_array = json_decode($json_string, true);
  7.     if(isset($json_array['annual_income']) && !empty($json_array['annual_income'])) {
  8.         // value is not null
  9.     } else {
  10.         // value is null or empty
  11.     }
  12. }
  13.  
  14. function method2($json) {
  15.     $annual_income1='"annual_income":""';
  16.     $annual_income2='"annual_income":null';    
  17.     if(strpos($json,$annual_income1) !== false || strpos($json,$annual_income2) !== false) {
  18.         // value is null or empty
  19.     }
  20. }
  21.  
  22. $start = microtime(true);
  23. for($i = 0; $i < 1000; $i++) {
  24.     method1($json_string);
  25. }
  26. $end = microtime(true);
  27. $elapsed_mehtod1 = round($end - $start, 6);
  28. echo 'Method 1 used: ' . $elapsed_mehtod1 . 's' . PHP_EOL;
  29.  
  30. $start = microtime(true);
  31. for($i = 0; $i < 1000; $i++) {
  32.     method2($json_string);
  33. }
  34. $end = microtime(true);
  35. $elapsed_mehtod2 = round($end - $start, 6);
  36. echo 'Method 2 used: ' . $elapsed_mehtod2 . 's' . PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement