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
  • 771
  • 3
  • 10
  • 31

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
  • 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