0

After changing web server, i get "

PHP Parse error: syntax error, unexpected '[' in ...".

I guess this is because I'm now using another version of PHP. Can't really figure out what the problem is. Can anyone help? The line that gets the error message is "if (count (json_decode ($result, true)['r']) != 0) {".

function g ($t) {
    $output = '';

    // Checking that there is a cpe hostname
    if (!empty ($t)) {
        // Getting the id of the device
        $curl = curl_init ();

        curl_setopt ($curl, CURLOPT_URL, '...=' . $t);
        curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt ($curl, CURLOPT_TIMEOUT, 5);

        $result = curl_exec($curl);

        curl_close ($curl);

        if (count (json_decode ($result, true)['r']) != 0) {
            // Getting the configuration for the device
            $curl = curl_init ();

            curl_setopt ($curl, CURLOPT_URL, '...=' . json_decode ($result, true)['r'][0]['id']);
            curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 3);
            curl_setopt ($curl, CURLOPT_TIMEOUT, 5);

            $result = curl_exec($curl);

            curl_close ($curl);

            // If the configuration of the device was found
            if (count (json_decode ($result, true)['c']['r']['c']) != 0) {
                $output = json_decode ($result, true)['c']['r']['c'];
            }
        }
    }

    return $output;
}

I tried looking for other posts here on Stackoverflow with simulare problems without any luck.

brombeer
  • 8,716
  • 5
  • 21
  • 27
tdekk
  • 1
  • 1
  • What version of PHP exactly? There are no syntax errors in this code, on any supported version: https://3v4l.org/fLScq – ADyson Feb 08 '23 at 13:12
  • It worked on PHP 5.6.40, but not on PHP 5.3.3. – tdekk Feb 09 '23 at 07:49
  • The solution to that really is to upgrade to a supported version and stop using one which went out of support 8 years ago!! You are leaving yourself vulnerable to all sorts of potential security problems, not to mention missing out on new features - including syntax enhancements (!), performance improvements etc. – ADyson Feb 09 '23 at 09:23
  • Anyway the issue in 5.3 seems to be using array syntax at the end of a function call. So instead you should just separate the function calls out, and use some variables. To be honest it makes the code a lot more readable anyway, and also reduces the number of times you are repeatedly decoding the JSON (which is inefficient). Try this version: https://3v4l.org/EA7O4#v5.3.29 – ADyson Feb 09 '23 at 12:39

0 Answers0