Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP syntax error, unexpected '[' in using an array [duplicate]

Tags:

php

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 other host, when i check the code, i see this error :

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

I have shown where the code causes error .

i have also used :

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

(without 0 in [])

How can i solve it ?

like image 919
Cab Avatar asked Dec 11 '22 05:12

Cab


2 Answers

Array Referencing was first added in PHP 5.4.

The code from PHP.net:

<?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'd have to change

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

to

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

If your PHP version is older than 5.4.

like image 55
h2ooooooo Avatar answered Feb 13 '23 05:02

h2ooooooo


The problem is this line:

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

Which is because you're using a version of PHP which doesn't support function array dereferencing, which was only added in PHP 5.4

To get around it, you'd have to call the method first, and then access its properties, eg:

$someVariable = $value->attributes();
$data[] = (string) $someVariable['data'];
like image 45
billyonecan Avatar answered Feb 13 '23 06:02

billyonecan