I want to do explode(" ",$q[2])[1]
where $q[2]
is a string reading "question 1" but I keep getting errors saying that a comma or semicolon were expected instead of the right facing square bracket after the explode "[1]
". I can use this syntax when the string isn't an array position so is there a shorthand way of doing this instead of making some temp variable and exploding it?
Asked
Active
Viewed 398 times
1

Craig Lafferty
- 771
- 3
- 10
- 31
-
3This will not work if your php version is < 5.4 – cornelb Feb 18 '14 at 21:03
-
Upgrade or $foo = explode(" ", $q[1]);$foo[1]; Consider if explode is really what you need.. – Ronni Skansing Feb 18 '14 at 21:05
-
Ahh, thank you. I just moved to a new hosting environment and neglected to think of the php version. – Craig Lafferty Feb 18 '14 at 21:06
-
possible duplicate of [PHP syntax for dereferencing function result](http://stackoverflow.com/questions/742764/php-syntax-for-dereferencing-function-result) – salathe Feb 18 '14 at 21:20
2 Answers
6
You can try with:
list($first, $second) = explode(" ",$q[2]);
So $second
variable is [1]
element from the return array.
$first // "question"
$second // "1"
It is also possible to omit $first
variable, so:
list(, $second) = explode(" ",$q[2]);

hsz
- 148,279
- 62
- 259
- 315
3
At PHP 5.3 or under, you can't index an expression. You have to split it into two lines:
x = explode(" ",$q[2]);
y = x[1];

hek2mgl
- 152,036
- 28
- 249
- 266

Damien Black
- 5,579
- 18
- 24