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?

4
  • 3
    This will not work if your php version is < 5.4 Commented Feb 18, 2014 at 21:03
  • Upgrade or $foo = explode(" ", $q[1]);$foo[1]; Consider if explode is really what you need.. Commented Feb 18, 2014 at 21:05
  • Ahh, thank you. I just moved to a new hosting environment and neglected to think of the php version. Commented Feb 18, 2014 at 21:06
  • possible duplicate of PHP syntax for dereferencing function result Commented Feb 18, 2014 at 21:20

2 Answers 2

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]);
Sign up to request clarification or add additional context in comments.

Comments

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.