Well, I disagree that json_decode()
has poor performance; I'll show you the proof below.
To achieve your task, you can use the following codes:
$json_string = '[{"highest_education":"B.E ( Automobile Engineering )","occupation":"Job in Private Office","annual_income":""}]';
$json_array = json_decode($json_string, true);
if(isset($json_array['annual_income']) && !empty($json_array['annual_income'])) {
// value is not null
} else {
// value is null or empty
}
There is no need to iterate through the JSON array at all.
Using PHP 7.1.16, I ran both methods for 1000 times, the performance difference between strpos()
and json_decode()
is not significant.
json_decode() used: 0.001691s
strpos() used: 0.00033s
Full test code is here: https://pastebin.com/ZcpjydfK, you can test it on your computer.
On the other side, there is a problem using strpos()
approach. There is a chance that the JSON string is malformed, or space is added between the colon :
, then your strpos()
checking won't work.