1

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?

Craig Lafferty
  • 779
  • 2
  • 10
  • 29

2 Answers2

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
  • 143,040
  • 58
  • 252
  • 308
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
  • 143,113
  • 25
  • 227
  • 253
Damien Black
  • 5,469
  • 16
  • 24