Unexpected '[' on return explode(" ", $message)[0]; - php

In PHP, I'm getting "Parse error: syntax error, unexpected '['" on the following line of code:
return explode(" ", $message)[0];
I'd give more details, but that's really about it. The line looks unimpeachable to me, and in fact was running fine until I copied it into another file. The biggest difference is that now that line is part of a class, and that it's being called by a big software library that I don't know much about. What could be causing this issue?
A bit more context:
public function getIRCCommand($message)
{
if ($message[0] != ":")
{
return explode(" ", $message)[0];
}
else
{
return preg_split("/\s+/", $message)[1];
}
}

You're likely running on PHP 5.3 or lower. You need to upgrade to at least PHP 5.4 to get this working (or use a temporary variable to access elements of a function returning an array).
What you're doing there is called array dereferencing. The manual says:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
As of PHP 5.5 it is possible to array dereference an array literal.
And, to check that, let's try to run
<?php
echo explode(" ", "1 2 3")[1];
for all kinds of diferent PHP versions. The results are, that PHP versions 5.4 and hihgher output "2", which would be your desired result.

Related

Php anonymous function with short array not work in 5.4.35

I have an odd issue with this php script
<?php
$expr = '["Nizky_tarif","Vysoky_tarif"][0 == 1]';
$newfunc = #create_function('', "return $expr;");
var_dump($newfunc);
echo $newfunc();
On server it crashes with error:
bool(false)
PHP Fatal error: Function name must be a string in /tmp/foo.php on line 7
On localhost it works:
string(9) "\000lambda_1"
Nizky_tarif
Server php version is 5.4.35, localhost 5.6.3. However I don't see why it wouldn't work, the short array syntax was added in 5.4, right?
ps. Just tried, if I change it to the old array syntax, it crashes also.
In the expression ["Nizky_tarif","Vysoky_tarif"][0 == 1] the code is trying to directly dereference an array literal. This is a feature which was introduced with PHP 5.5.
With PHP 5.4 this expression is not valid, resulting in the error "Function name must be a string".
You could change that into to parts to make it work:
$data = ["Nizky_tarif","Vysoky_tarif"];
return $data[0 == 1];

PHP gives unexpected [ - but why?

having strange trouble with this:
date_parse('2014-08-26')['hour']
It works on a php command line.
But this throws an error:
if(date_parse('2014-08-26')['hour']){ echo "works";}
syntax error, unexpected '['
Why is that? The result should be any number between 0 and 23 or nothing, nothing would it be in this case.
EDIT: yes, I am on PHP 5.3.14
Please note that versions of PHP older than 5.4 can not access array attributes from a functions return value directly. You have to store the functions return value in a new variable and access the array from that variable.
So this code
if(date_parse('2014-08-26')['hour']){ echo "works";}
only works on PHP 5.4 and higher. If you run a PHP version lower then 5.4 your code should look like this:
$parseResult = date_parse('2014-08-26');
if($parseResult['hour']) { echo "works"; }
You must be using below 5.4 version of PHP. If so than please use the latest version of php as the version below 5.4 does not allow brackets [].
Before version 5.4, PHP didn't allow you to dereference elements of arrays returned from function calls without using a temporary variable:
http://php.net/manual/en/language.types.array.php#example-102
$cond = date_parse('2014-08-26')['hour'];
if($cond)
{
echo "works";
}
Hope this works

PHP syntax error in different versions

I sometimes get values from an array like this: $var = array ('key1' => 'value1')['key1']; , so $var should be equal to value1
I run code like this in a server having PHP v5.4.16 , for example, explode ('-', $str)[0]; and it works fine.
Now if I transfer this code to another server which uses PHP v5.3.10 I get an error (syntax error): syntax error, unexpected '[' ...
Is this because of the version? (I don't think so because the difference between versions is so small..), or some setting in the server?
Can anyone enlighten me?
Yes, it depends on the version of PHP you are running. As PHP docs mentions
As of PHP 5.4 it is possible to array dereference the result of a
function or method call directly. Before it was only possible using a
temporary variable.
As of PHP 5.5 it is possible to array dereference an array literal.
In PHP 5.3 you would have to use
$exploded = explode('-', $str);
$first = $exploded[0];
// or
list($first,) = explode('-', $str);
In PHP 5.4 and later you can use
$first = explode('-', $str)[0];

PHP cannot automatically use function result as array (in PHP 5.3)

When I try to run something like
getParent($child)[0]->user
I get the following error:
PHP Parse error: syntax error, unexpected '[', expecting ')' in /.....
The problem can be avoided if I do something like this:
$get_parent = getParent($child);
$parent = $get_parent[0]->user;
Is there a better way to do in php 5.3
No, before PHP5.4, you have to do that.
Array dereferencing comes from PHP 5.4.
But if getParent return an object which implement the ArrayAccess interface, you could chain it with:
$parent = getParent($child)->offsetGet(0)->user;
If it just return an array, then a temp variable is necessary.
Actually, there is a way to achieve that without temporary variable. But I definitely wouldn't recommend to use it (because, yes, it's one-liner and it's not using temporary variable, but no - it's not readable):
function getParent($child=null)
{
//mock:
return array(
(object)(array('user'=>'foo', 'data'=>'fee')),
(object)(array('user'=>'bar', 'data'=>'bee')),
);
};
//array(null) will have 1 key, 0;
//however, to get another offset N, use array(N => null) instead
$result = array_shift(array_intersect_key(getParent('baz'), array(null)))->user;
-so use temporary variable if your version in <5.4
Where it may be helpful - is in debugger, where you're forced to use "one-liners" to check some expression(s)
There is no better way to do it when using PHP version < 5.4.
If you still want to use one line instead of 2 and you always want to get the first element, you can try the following
echo reset(getParent($child))->user;
This reset the array pointer to 0 and returns the value.

PHP 5.4 to 5.3 Conversion

Are their any good resources when you are trying to get a PHP script written in a newer version to work on an older version; Specifically 5.4 to 5.3?
I have even checked out articles about the changes and I cannot seem to figure out what I am doing wrong.
Here is the error I am getting, at this moment:
Parse error: syntax error, unexpected '[' in Schedule.php on line 113
And the code it is referring to:
private static $GAMES_QUERY = array('season' => null, 'gameType' => null);
.....
public function getSeason(){
$test = array_keys(self::$GAMES_QUERY)[0]; //<<<<<<<<<< line:113
return($this->query[$test]);
}
Everything I have seen seems to say that 5.3 had self::, array_keys, and the ability to access arrays like that.
try...
$test = array_keys(self::$GAMES_QUERY);
$test = $test[0];
If I'm not mistaken, you can't use the key reference [0] in the same declaration in 5.3 like you can in 5.4 and javascript, etc.
That syntax was actually added in 5.4: http://docs.php.net/manual/en/migration54.new-features.php
So, you'll need a temporary variable to hold the result of the function, then access the index you want.
In versions lower than PHP 5.4 for the case you have you can make use of the list keywordDocs:
list($test) = array_keys(self::$GAMES_QUERY);
That works in PHP 5.4, too. But it does deal better with NULL cases than the new in PHP 5.4 array dereferencingDocs.

Categories