Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to assign empty value if the parameter not exist in php

Tags:

json

post

php

slim

I'm getting some JSON response from one server URL, The response parameters may change based on the user credentials,

For example, sometimes it will return user state,sometimes it will customer state both have same value but I need to handle like if any state parameter is not coming by default take empty,so I tried the below logic.

$centre_jurisdiction = $data['data']['ctj'] ?? "";
$state_jurisdiction = $data['data']['stj'] ?? "";

The above logic is perfectly working fine in my localhost but it's not working in my live server then I found the reason,it's not working in my live server because my live server PHP version is 5.0 and it's working in my localhost because my localhost PHP version is 7.0.

I need to make this logic working in my live server too without updating my live server PHP version because some old projects also hosted in that server and those will be supported in PHP 5.

Is there any alternative to handle this logic? Thanks!

like image 501
Prabaharan Rajendran Avatar asked Dec 11 '22 07:12

Prabaharan Rajendran


2 Answers

You face problems with PHP 5, because the null coalescing operator was introduced in PHP 7.

An equivalent to that would be using a conditional operator along with isset.

$centre_jurisdiction = isset($data['data']['ctj']) ? $data['data']['ctj'] : "";
$state_jurisdiction = isset($data['data']['stj']) ? $data['data']['stj'] : "";
like image 168
Angel Politis Avatar answered Jan 13 '23 11:01

Angel Politis


The null coalescing operator "??" is just syntactic sugar that was added in PHP 7; see the Manual. You can also think of it as the "isset ternary" operator; see the RFC.

So, the good news is that that one may rewrite the code as follows for PHP 5:

$centre_jurisdiction = isset($data['data']['ctj'])? $data['data']['ctj'] : "";

$state_jurisdiction = isset($data['data']['stj'])?  $data['data']['stj'] : "";

Note: the logic is the same but the syntax is shorter and thus sweeter in PHP 7. The PHP 5 code simply makes everything explicit.

like image 27
slevy1 Avatar answered Jan 13 '23 09:01

slevy1