4

I want to do

<?php 
$str = "I want to access 2nd or 3rd index in one line";
echo explode(" ",$str)[2];
?>

We can access first index easily using

stristr($str," ",true);  //For php version >= 5.3

or

$foo = array_shift(explode(':', $foo));

or

list($str) = explode(" ", $str);

BUT

HOW TO ACCESS SPECIFIC INDEX [1],[2] OR [3] IN ONE LINE???

2
  • 2
    You can only do echo explode(" ",$str)[2]; in PHP >= 5.4 as I remember. Commented Jun 13, 2013 at 7:13
  • yes, you are correct, i just tested it in 5.4, any other good solution to work with other version will be appreciated :) Commented Jun 13, 2013 at 7:16

3 Answers 3

3

5.4+

<?php echo explode(" ","I want to access 2nd or 3rd index in one line")[2]; ?>
Sign up to request clarification or add additional context in comments.

2 Comments

He wants to have it working in 5.3 :) see the comments beneath the OP's post.
Those comments were posted after the answer
0

for second

strtok($string, " "); echo strtok(" ");

or third

strtok($string, " "); strtok(" "); echo strtok(" ");

Comments

-1

Try like this to get specific index value

<?php 
  $str = "Iam want to access 2nd or 3rd index in one line";
  $val = explode(" ",$str);
  echo $val[3];
?>

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.