1

I have some code that looks for a branch of a JSON string called applications and then for each item it finds, it executes some code.

This works fine if the JSON contains "applications" but falls over if it doesn't.

My PHP

$json = file_get_contents("programs.json");
$array = json_decode($json, true);
foreach ($array['applications'] as $app) {
    $application = $app['application'];
    // Do some stuff
}

My JSON looks like this:

{
    "hostname": "MINIPC025",
    "applications": [{
            "application": "7-Zip 19.00 (x64)"
        },
        {
            "application": "Active Directory Rights Management Services Client 2.1"
        },
        {
            "application": "Adobe Acrobat Reader DC MUI"
        }
    ]
}

So my question is - is it possible to put some kind of if statement that says only loop through the applications bit of the JSON data if the applications property exists.

Thank you.

Qirel
  • 25,449
  • 7
  • 45
  • 62
Ed Mozley
  • 3,299
  • 4
  • 15
  • 20

3 Answers3

3

There are many ways to Rome, as they say. A simple if, where you can use a variety of native PHP functions, but also the usage of the null-coalescing operator ??.

They all end up with the same idea -- just iterate over $array['applications'] if it exists. None of these checks will actually check if its an iterable variable though, so if $array['applications'] = 'myString';, you will still receive errors. You can use the native PHP function is_iterable() to check that.

Using null-coalescing operator ??

foreach ($array['applications'] ?? [] as $app) {
    // ...
}

Using array_key_exists()

if (array_key_exists('applications', $array)) {
    foreach ($array['applications'] as $app) {
        // ...
    }
}

Using isset()

if (isset($array['applications'])) {
    foreach ($array['applications'] as $app) {
        // ...
    }
}

Using !empty()

if (!empty($array['applications'])) {
    foreach ($array['applications'] as $app) {
        // ...
    }
}

Of the above here, I'd recommend using either isset()/!empty() or the null-coalescing operator, as array_key_exists() will still return true for the case of $array['applications'] = null;.

Some useful, related reading

Qirel
  • 25,449
  • 7
  • 45
  • 62
0

You could use isset to check if a variable is declared and is different than NULL

if(isset($array['applications'])){
    foreach ($array['applications'] as $app)
  ...
}
Aashish gaba
  • 1,726
  • 1
  • 5
  • 14
  • Warning: This answer will not work if the value of `$array['applications']` is not iterateable. – meewog Jul 29 '20 at 09:06
0

You can use

property_exists($json, 'applications')

$json = file_get_contents("programs.json");
$array = json_decode($json, true);

if (property_exists($array, 'applications')) {
    foreach ($array['applications'] as $app) {
        $application = $app['application'];
        // Do some stuff
    }
}

Works only if json is object.