0

I get some user information from linked api as json objects. I parse the json using json_decode method. It works just fine. My problem is when a field doesn't exist in the json. For example position object sometimes won't have the endDate property.

$endDate = $user->positions->values[$i]->endDate->year."-".$user->positions->values[$i]->endDate->month."-01"; 

when the endDate property doesn't exist it gives me the undefined property error. and code fails. I tried to use try catch but it still gives the error in try. im a newbie php coder. How should I detect that a property is undefined before making a call to that property?

0

2 Answers 2

1

You can verify if a field exists the following way :

if (isset($user->positions->values[$i]->endDate))
{
    $endDate = $user->positions->values[$i]->endDate->year."-".$user->positions->values[$i]->endDate->month."-01";
}
else
{
    $endDate = null; // Or whatever you want it to be
}
Sign up to request clarification or add additional context in comments.

Comments

0

Starting on PHP/7.0, you can use the null coalescing operator to avoid the error and set a default value:

$json = <<<JSON
{
    "positions": {
        "values": [
            {
                "endDate": {
                    "year": 2024,
                    "month": 1 
                }
            },
            {
                "anotherKey": true
            }
        ]
    }
}
JSON;
$user = json_decode($json);

foreach ($user->positions->values as $i => $value) {
    var_dump($i, $value->endDate->year ?? null, $value->endDate->month ?? null);
}
int(0)
int(2024)
int(1)
int(1)
NULL
NULL

The code in the question needs to concatenate two possibly missing items, so it can use a small refactoring:

for ($i = 0; $i < 2; $i++) {
    $endDate = $user->positions->values[$i]->endDate ?? null
        ? $user->positions->values[$i]->endDate->year . "-" . $user->positions->values[$i]->endDate->month . "-01"
        : null;
    var_dump($i, $endDate);
}
int(0)
string(9) "2024-1-01"
int(1)
NULL

But, admittedly, good old isset() is a better fit.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.