9

I'm looking for the quickest/shortest way to get the first value from comma separated string, in-line.

The best I can do is

$string = 'a,b,c,d';
echo "The first thing is " . end(array_reverse(explode(',', $string))) . ".";

but I feel that's excessive and redundant. Is there a better way?

Steve Robbins
  • 13,672
  • 12
  • 76
  • 124

5 Answers5

9
list($first) = explode(',', 'a,b,c,d');
var_dump($first);  // a

probably works :)


In PHP 6.0 you will be able to simply:

$first = explode(',', 'a,b,c,d')[0];

But this is a syntax error in 5.x and lower

Halcyon
  • 57,230
  • 10
  • 89
  • 128
8

Steve

It's little bit shorter

strtok('a,b,c,d', ",")
Oleg Matei
  • 866
  • 13
  • 9
6

How about

echo reset(explode(',', 'a,b,c,d'))
itsmeee
  • 1,627
  • 11
  • 12
4
<?php    
$array = explode(',', 'a,b,c,d');
$first = $array [0];
Jeroen
  • 13,056
  • 4
  • 42
  • 63
1
        $int = substr($string,0,strpos($string,","));
kamran
  • 93
  • 11
  • 2
    Please provide some detail about what are you doing for further detail! – Farbod Ahmadian Aug 18 '20 at 11:21
  • Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users also with similar issues. – FluffyKitten Aug 18 '20 at 17:49