PHP syntax error, unexpected '[' when using array

I am using this code below:

$data = array();
$value = reset($value);
$data[0] = (string) $value->attributes()['data'];
------^

I have no problem in localhost, but in another host, when I check the code, I see this error:

Analysis error: syntax error, unexpected '[' in ....

I showed where the code is causing the error.

i also used:

$data[] = (string) $value->attributes()['data'];

(without 0in [])

How can i solve this?

+4
source share
2 answers

Array summarization was first added in PHP 5.4 .

PHP.net Code:

<?php
function getArray() {
    return array(1, 2, 3);
}

// on PHP 5.4
$secondElement = getArray()[1];

// previously
$tmp = getArray();
$secondElement = $tmp[1];

// or
list(, $secondElement) = getArray();
?>

So you have to change

$data[] = (string)$value->attributes()['data'];

to

$attributes = $value->attributes();
$data[] = (string)$attributes['data'];

If your version of PHP is older than 5.4.

+8
source

The problem is this line:

$value->attributes()['data'];

, PHP, , ​​ PHP 5.4

, , , :

$someVariable = $value->attributes();
$data[] = (string) $someVariable['data'];
+5

Source: https://habr.com/ru/post/1543196/


All Articles